我有VBA代码,运行sql服务器存储的proc,将数据导入excel。
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的一个用户运行VBA宏,excel结果应该只显示Division北方。如果来自South的用户运行VBA宏,excel结果应该只显示Division South。
例:如果来自South的一个用户运行VBA宏,结果如下
Id Division Department Scale
2 South Finance 8.0
6 South IT 8.5如何通过Division设置用户以过滤VBA中的数据。
我被限制了。大多数是4-6个用户。是否可以通过在VBA中添加一些代码来使用他们的windows凭据来过滤excel中的数据?
有什么帮助吗?
发布于 2015-04-08 16:39:14
因为您有少量的用户,所以可以在您的VBA项目中直接对其进行硬编码。为此,我将使用字典对象。字典是将数据存储在键值对中的一种方法。
让我们深入研究一些代码。
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属性.->保护并勾选“查看锁定项目”框并输入密码。
我应该补充一点,使用这种字典方法有其局限性。例如,如果需要将一个用户分配到多个区域,这将不能作为每个键工作,则值对必须是唯一的。
如果是这样的话,我将研究如何处理这个服务器端。您可以创建一个具有用户名、区域对的新sql表。然后,您可以将用户名作为参数传入SQL存储过程,并使用该参数来控制该过程返回的结果。这最终可能是更可取的。
发布于 2015-04-07 00:31:07
是啊。Environ("username")提供了windows登录,对于4-6个用户,您甚至可以从这里硬编码南北映射,当然也可以将其设置为excel中的范围,或数据库表和查找方式。
发布于 2015-04-07 12:30:33
你的答案就在这个回答里。
我认为你需要这样的解决方案:
UserName和Direction )的数据集来指定指向某个方向的任何用户。UserName = Environ("username")来查找特定的用户。Direction之后,您应该按照这条线索过滤所有工作表,就像隐藏不位于该方向的行一样。https://stackoverflow.com/questions/29481649
复制相似问题