vbadatabasems-accessms-forms

Passing a variable from one form to another


I created a login screen for my DB which works.

I would like to pass a variable to a text box that will be on the 'Main Menu' form once you're validated.

Here's my code when you click '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

This line displays a prompt on screen saying Login successful with the "rst.Fields(0).Value" variable which is the users full name, but I'd prefer less windows and buttons to press and instead, pass this variable to a new blank form with a textbox on it.

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

I named the textbox on the MainMenu form, txt_welcome.

I tried appending the below in the IF statement:

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"

Solution

  • You can pass it through the OpenArgs parameter of the DoCmd.OpenForm method.

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

    Then, on the MainMenu form, read its value when the form loads:

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