将变量从一种形式传递到另一种形式

Passing a variable from one form to another

我为我的数据库创建了一个可用的登录屏幕。

我想将一个变量传递给验证后 'Main Menu' 表单上的文本框。

这是我点击 'Login' 时的代码。

'Login button submit, validate, welcome message & main menu navigation
Private Sub cmd_login___Click()

    Dim db As DAO.Database
    Dim rst As DAO.Recordset
    Dim strSQL As String
 
    'query to check if login details are correct
    strSQL = "SELECT Name FROM LoginQuery WHERE Username = """ & Me.txt_username.Value & """ AND Password = """ & Me.txt_password.Value & """"
  
    Set db = CurrentDb
    Set rst = db.OpenRecordset(strSQL)
    If rst.EOF Then
        MsgBox prompt:="Incorrect username/password. Try again.", buttons:=vbCritical, title:="Login Error"
        Me.txt_username.SetFocus
    Else
        MsgBox prompt:="Hello, " & rst.Fields(0).Value & ".", buttons:=vbOKOnly, title:="Login Successful"
        DoCmd.Close acForm, "frm_login", acSaveYes
        DoCmd.Close
        DoCmd.OpenForm "MainMenu"
    End If
 
    Set db = Nothing
    Set rst = Nothing

这一行在屏幕上显示一条提示,提示使用“rst.Fields(0).Value”变量登录成功,这是用户的全名,但我更喜欢少一些 windows 和按钮按下 ,而是将此变量传递给一个带有文本框的新空白表单。

MsgBox prompt:="Hello, " & rst.Fields(0).Value & ".", buttons:=vbOKOnly, title:="Login Successful"

我将 MainMenu 表单上的文本框命名为 txt_welcome.

我尝试在 IF 语句中附加以下内容:

Dim name As String
name = "SELECT Name FROM LoginQuery WHERE Username = """ & Me.txt_username.Value & """ AND Password = """ & Me.txt_password.Value & """"
[MainMenu]![txt_welcome].Value = name

[MainMenu]![txt_welcome].Value = "dsfadsf"

MainMenu!txt_welcome.value = "justdisplaysomethingplz"

可以通过DoCmd.OpenForm方法的OpenArgs参数传递。

DoCmd.OpenForm "MainMenu", OpenArgs:="Something"

然后,在 MainMenu 窗体上,加载窗体时读取其值:

Private Sub Form_Load()
    If Not IsNull(OpenArgs) Then Debug.Print OpenArgs
End Sub