Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing variable from Form to Module in VBA

Tags:

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.

like image 878
JimmyK Avatar asked Nov 26 '13 10:11

JimmyK


People also ask

How to pass variables from a userform to a module?

Re: Pass variables from userform to module. Well you can pass variables in functions, or by having public variables, you can also call a module and refer to the form through it's object - there are drawbacks to each, all of which make things more complicated You'd be better putting the code that the userform uses in the userform,...

Is it possible to pass data from a userform to a sub?

In theory you could pass data from a userform to a sub in a standard module but it wouldn't be particularly straightforward. Especially when it appears you want to pass data from the userform to the sub that shows the userform. When you show the userform code controls passes to it.

What should be in the standard module of a form?

The only thing that should be in the standard module should probably be the one line that is used to show the userform. The rest of the code in that module can probably be moved to the userform's module, probably after the line of code that hides the form.

How to avoid using global variables in a module?

You need to assign global variables a value in a module Avoid the public variables until and unless it is absolutely necessary. Pass the relevant value as a parameter as shown in the link below the question. Ohh, you mean just avoiding globals in general, thought there was some other way of assigning and not to do it in a module.


1 Answers

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.

like image 55
Siddharth Rout Avatar answered Oct 07 '22 22:10

Siddharth Rout