Passing variable from Form to Module in VBA Passing variable from Form to Module in VBA vba vba

Passing variable from Form to Module in VBA


Don't declare the variable in the userform. Declare it as Public in the module.

Public pass As String

In the Userform

Private Sub CommandButton1_Click()    pass = UserForm1.TextBox1    Unload UserForm1End Sub

In the Module

Public pass As StringPublic Sub Login()    '    '~~> Rest of the code    '    UserForm1.Show    driver.findElementByName("PASSWORD").SendKeys pass    '    '~~> Rest of the code    'End Sub

You might want to also add an additional check just before calling the driver.find... line?

If Len(Trim(pass)) <> 0 Then

This will ensure that a blank string is not passed.


Siddharth's answer is nice, but relies on globally-scoped variables. There's a better, more OOP-friendly way.

A UserForm is a class module like any other - the only difference is that it has a hidden VB_PredeclaredId attribute set to True, which makes VB create a global-scope object variable named after the class - that's how you can write UserForm1.Show without creating a new instance of the class.

Step away from this, and treat your form as an object instead - expose Property Get members and abstract away the form's controls - the calling code doesn't care about controls anyway:

Option ExplicitPrivate cancelling As BooleanPublic Property Get UserId() As String    UserId = txtUserId.TextEnd PropertyPublic Property Get Password() As String    Password = txtPassword.TextEnd PropertyPublic Property Get IsCancelled() As Boolean    IsCancelled = cancellingEnd PropertyPrivate Sub OkButton_Click()    Me.HideEnd SubPrivate Sub CancelButton_Click()    cancelling = True    Me.HideEnd SubPrivate Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)    If CloseMode = VbQueryClose.vbFormControlMenu Then        cancelling = True        Cancel = True        Me.Hide    End IfEnd Sub

Now the calling code can do this (assuming the UserForm was named LoginPrompt):

With New LoginPrompt    .Show vbModal    If .IsCancelled Then Exit Sub    DoSomething .UserId, .PasswordEnd With

Where DoSomething would be some procedure that requires the two string parameters:

Private Sub DoSomething(ByVal uid As String, ByVal pwd As String)    'work with the parameter values, regardless of where they came fromEnd Sub