Home > Software design >  MSoft Access - Passing a variable from one form to another
MSoft Access - Passing a variable from one form to another

Time:11-10

I've created a login screen for my DB which works and I would like to pass on 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 of code here:

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

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.

I named the textbox on the MainMenu form, txt_welcome.

I admit I've spent far too long on this, I've 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"

Nothing works, please can someone help me with this, It would appear to be easy on the surface level but the tutorials are either out of date or too complex. Thanks

CodePudding user response:

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
  • Related