无法在MS-Access中的子中使用函数的变量
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了无法在MS-Access中的子中使用函数的变量相关的知识,希望对你有一定的参考价值。
我的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
sub中使用Load()
获取值,但无法使用GetEmpID
获取值。
可能的原因是什么?我该如何解决?
提前致谢。
答案
选项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
警告:从内存中键入内容。可能需要进行小的修正。
另一答案
您可以随时在函数中使用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的详细说明,请参阅以下网站
以上是关于无法在MS-Access中的子中使用函数的变量的主要内容,如果未能解决你的问题,请参考以下文章
使用包含 SUM() 字段的子查询在 MS-Access 中编辑查询