Passing variable from Form to Module in VBA

JimmyK picture JimmyK · Nov 26, 2013 · Viewed 116.2k times · Source

I have the following button on a Form:

Private Sub CommandButton1_Click()
 Dim pass As String
 pass = UserForm1.TextBox1
 Unload UserForm1
End Sub

I then have a Module called Module1:

 Public Sub Login()

 ...

 UserForm1.Show
 driver.findElementByName("PASSWORD").SendKeys pass

 ...

End Sub

The idea is whatever password the users enters into the input box will be assigned to the variable pass. What I'm having trouble doing however is passing pass from UserForm1 into Module1's Login sub.

I would of thought adding something like Module1.Login (pass) to my form before I unload it would work, however that doesn't seem to pass anything. Any help would be much appreciated. Thanks.

Answer

Siddharth Rout picture Siddharth Rout · Nov 26, 2013

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 UserForm1
End Sub

In the Module

Public pass As String

Public 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.