我的ms-access表单上有以下VBA代码
Option Compare Database
Option Explicit
Public Function GetUserName() As String
Dim obj1 As Object
Dim GetEmpID As String
Set obj1 = CreateObject("WScript.Network")
GetUserName = DLookup("[BAFUser]", "BAF_User", "[BRID] = '" & obj1.UserName & "'")
GetEmpID = DLookup("[EmpID]", "BAF_User", "[BRID] = '" & obj1.UserName & "'")
Set obj1 = Nothing
End Function
Private Sub Form_Load()
Me.EmpName.Value = GetUserName
Me.EmpID.Value = GetEmpID
End Sub
我可以使用GetUserName
子信息中的Load()
获取值,但无法使用GetEmpID
获取值。
可能的原因是什么?我该如何解决?
提前致谢。
答案 0 :(得分:2)
选项1:创建模块级变量,您在函数中设置(现在是子级,因为它没有返回值)
Option Compare Database
Option Explicit
Dim UserName as String
Dim EmpID as String
Public Sub GetValues()
Dim obj1 As Object
Set obj1 = CreateObject("WScript.Network")
UserName = DLookup("[BAFUser]", "BAF_User", "[BRID] = '" & obj1.UserName & "'")
EmpID = DLookup("[EmpID]", "BAF_User", "[BRID] = '" & obj1.UserName & "'")
Set obj1 = Nothing
End Sub
Private Sub Form_Load()
Call GetValues() 'Invoke the function to set values
Me.EmpName.Value = UserName 'retrieve values from module level variables
Me.EmpID.Value = EmpID
End Sub
选项2:创建ByRef变量。
Option Compare Database
Option Explicit
Public Sub GetValues(ByRef UserName as String, ByRef EmpID as String)
Dim obj1 As Object
Set obj1 = CreateObject("WScript.Network")
UserName = DLookup("[BAFUser]", "BAF_User", "[BRID] = '" & obj1.UserName & "'")
EmpID = DLookup("[EmpID]", "BAF_User", "[BRID] = '" & obj1.UserName & "'")
Set obj1 = Nothing
End Sub
Private Sub Form_Load()
Dim UserName as String
Dim EmpID as String
Call GetValues(UserName, EmpId) 'Invoke the function to set values of local variables.
Me.EmpName.Value = UserName 'retrieve values from function scoped variables.
Me.EmpID.Value = EmpID
End Sub
警告:从内存中键入内容。可能需要进行小的修正。
答案 1 :(得分:1)
您可以随时在函数中使用ByRef。
Option Compare Database
Option Explicit
Public Function GetUserName(ByRef GetEmpID as string) as string
dim obj1 as object
Set obj1 = CreateObject("WScript.Network")
GetUserName = DLookup("[BAFUser]", "BAF_User", "[BRID] = '" & obj1.UserName & "'")
GetEmpID = DLookup("[EmpID]", "BAF_User", "[BRID] = '" & obj1.UserName & "'")
If not obj1 is nothing then
Set obj1 = Nothing
End If
End Function
Private Sub Form_Load()
Dim GetEmpID as string
GetEmpID = "None"
Me.EmpName.value = GetUserName(GetEmpID)
Me.EmpID.Value = GetEmpID
End Sub
ByRef传递用于将变量存储在内存中的地址。一旦传递了地址而不是仅传递了值,地址上发生的任何更改都将在整个项目中对变量进行。
有关ByVal和ByRef的更多详细说明,请参阅以下网站: http://www.cpearson.com/excel/byrefbyval.aspx