VBA代码来自动筛选数据由Windowslogin用户ID?

我得到了运行sql server存储过程的VBA代码,将数据导入到excel中。

EX:Excel数据:

Id Division Department Scale 1 North IT 8.5 2 South Finance 8.0 3 North Finance 8.0 4 West IT 8.5 5 East Finance 8.0 6 South IT 8.5 

现在我得到的情况是:

如果North一个用户运行VBAmacros,则Excel结果应该只显示Division North。 如果来自South用户运行VBAmacros,则Excel结果只应显示Division South。

EX:如果来自South一个用户运行VBAmacros,结果如

 Id Division Department Scale 2 South Finance 8.0 6 South IT 8.5 

我如何根据Division设置用户来筛选VBA中的数据。

我有限的用户数量大多是4-6个用户。 有没有办法使用他们的Windows凭据在Excel中通过在VBA中添加一些代码来过滤数据?

任何帮助?

由于您的用户数量很less,您可以直接在您的VBA项目中对其进行硬编码。 为此,我将使用Dictionary对象。 字典是将数据存储在键值对中的一种方式。

让我们深入一些代码。

 Sub Test() Dim dict As Object Dim key As Variant Dim user As String Dim region As String Set dict = CreateObject("Scripting.Dictionary") 'Add your username / region 'pairs to the dictionary object dict.Add "user1", "South" dict.Add "user2", "North" dict.Add "user3", "South" dict.Add "user4", "West" '.. etc 'Get the username of the currently logged-in person user = Environ("username") 'Loop through dictionary to find the 'region which matches the username For Each key In dict.Keys If key = user Then region = dict.Item(key) End If Next key 'If the username is not found, we should 'exit the subroutine. You could display 'a messagebox or something similar If region = vbNullString Then MsgBox "Invalid username!", vbCritical, "Invalid Username" Exit Sub End If 'From hereon out you would do as you 'normally do, passing in the variable 'region as one of your parameters End Sub 

如果你不希望用户看到其他用户被分配到哪个区域,你应该用密码保护你的VBA代码。 你可以通过工具 – > VBAProject Properties … – > Protection来做到这一点,然后勾选'Lock project for viewing'框并input密码。

我应该补充说,使用这个字典方法有一定的局限性 例如,如果一个用户需要分配给多个区域,则这不会起作用,因为每个键,值对必须是唯一的。

如果是这样的话,我会考虑处理这个服务器端。 你可以创build一个新的具有用户名,区域对的sql表。 然后,您可以将用户名作为parameter passing给SQL存储过程,并使用该参数来控制过程返回的结果。 这最终可能是更可取的。

是的。 Environ(“用户名”)给出了windowslogin,对于4-6个用户,你甚至可以硬编码南北的映射,或者当然也可以把它设置为excel的范围或者数据库表和查找办法。

你的答案就在这个答案中 。

我认为你需要这样的解决scheme:

  • 您需要一个至less包含“ UserName和“ Direction这样的列的数据集,以便将任何用户指定为某个方向。

  • 现在你有你的UserName = Environ("username") ,可以让你find一个特定的用户。

  • 从数据集中find“ Direction ,您应该按照该线索过滤所有工作表,如隐藏不在该方向的行。

  • 如果你想有一个filter,使得他或她无法访问其他行的文件开启器,您还需要编写一些代码来保护该数据表。