在 VBA 中定义和调用全局变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33088100/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Defining and calling a global variable in VBA
提问by Rynoc
I have a login screen which compares data via a Dlookup in order to authenticate users. I would like to create a global variable upon a correct login that any form on the database can call on and then open a form based on what that value is. So currently I have everything set up as such. LOGIN FORM :
我有一个登录屏幕,它通过 Dlookup 比较数据以对用户进行身份验证。我想在正确登录后创建一个全局变量,数据库上的任何表单都可以调用该变量,然后根据该值打开一个表单。所以目前我已经把一切都设置好了。登录表格 :
Option Compare Database
Public gstrUsr As String
LOGIN FORM:
登录表格:
Public Sub Command4_Click()
'Sets the login time to now and then authenticates user credentials
Dim usr As String
Me.Time = Now
Dim lvl As String
Dim lck As Integer
Dim sql As String
Dim msgapp As Integer
Dim chkusr As Variant
chkusr = Nz(DLookup("[Username]", "Login", "[Username]='" & Me.Username.Value & "'"), "")
msgapp = 0
usr = Nz(DLookup("[Password]", "Login", "[Username]='" & Me.Username.Value & "'"), "")
lvl = Nz(DLookup("[Level]", "Login", "[Username]='" & Me.Username.Value & "'"), "")
sql = "INSERT INTO Log ( [User], [Time] )SELECT [Forms]![Login]![Username] AS Expr1, [Forms]![Login]![Time] AS Expr2;"
''" & [Forms]![ItemList1]![SRCB] & "'"
'Runs above sql which adds a time record for the selected username also removes the "You are about to update X rows", will use this in the future on the accounting functions
If chkusr = "" Then msgapp = 1
If chkusr = "" Then MsgBox ("Invalid Credentials")
DoCmd.SetWarnings False
DoCmd.RunSQL (sql)
DoCmd.SetWarnings True
'If password is = to the value that is returned in the "usr" variable declared at the top via Dlookup it will open a form based on what that users "level" is otherwise displays and invalid credentials message box
Do While msgapp = 0
If usr = Me.Password.Value Then
lck = 1
msgapp = 3
Else
MsgBox ("Invalid Credentials")
msgapp = 3
End If
Loop
Do While lck = 1
If lvl = "2" Then
DoCmd.OpenForm "MainB"
gstrUsr = DLookup("[Username]", "Login", "[Username]='" & Me.Username & "'")
lck = 0
Else
DoCmd.OpenForm "Main"
lck = 0
End If
Loop
End Sub
FORM THAT LOADS AFTER SUCCESSFUL LOGIN: (Main form with buttons to get to other forms, I included a text box so I could see if the information is being passed to the second form)
成功登录后加载的表单:(主表单带有用于访问其他表单的按钮,我包含了一个文本框,以便我可以查看信息是否正在传递到第二个表单)
Private Sub Form_Load()
Me.Text75 = gstrUsr
End Sub
How do I get the global variable to pass to the second form?
如何让全局变量传递给第二种形式?
回答by Máté Juhász
Define your public variable in a code module instead of the module of the form.
在代码模块而不是表单模块中定义公共变量。
This way it'll be available from any module (if it's public)
这样它就可以从任何模块中获得(如果是public)

