在VBA中定义和调用全局变量

Ryn*_*noc 0 ms-access vba

我有一个登录屏幕,它通过 Dlookup 比较数据以验证用户身份。我想在正确登录时创建一个全局变量,数据库上的任何表单都可以调用该变量,然后根据该值打开一个表单。所以目前我已经把一切都设置好了。登录表单 :

Option Compare Database
Public gstrUsr As String
Run Code Online (Sandbox Code Playgroud)

登录表单:

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
Run Code Online (Sandbox Code Playgroud)

成功登录后加载的表单:(带有用于访问其他表单的按钮的主表单,我包含一个文本框,以便我可以查看信息是否正在传递到第二个表单)

Private Sub Form_Load()
Me.Text75 = gstrUsr
End Sub
Run Code Online (Sandbox Code Playgroud)

如何将全局变量传递给第二种形式?

Mát*_*ász 5

在代码模块而不是表单模块中定义公共变量。

这样它就可以从任何模块使用(如果是的话public