I have a VBA project with a Module and a Userform. I want to use some variables from my module in my Userform.
Is it necessary that I declare these variables globally? I don't like global variables because they stay in memory after the code's execution, and I have to reset these variables one-by-one at the beginning of my macro. I can't use the keyword End to clear the variables from memory because I need to remember one or two of these variables. How do people usually do?
Edit: is there a way to pass a variable from the Userform to the module without creating a global variable?
The best way to share global variables across modules across a single program is to create a config module. Just import the config module in all modules of your application; the module then becomes available as a global name. Hope it works!!
Local Variables in Python A variable that is declared inside a python function or a module can only be used in that specific function or Python Module. This kind of variable is known as a local variable.
A local variable can be accessed from anywhere in the program. Different functions can have local variables with the same names. Python allows you to pass multiple arguments to a function. To assign a value to a global variable in a function, the global variable must be first declared in the function.
Create a Public Property in your userform and pass the variable into the form using the property. Useforms are just class module except that they have a user interface component. Example: In your userform's code module
Option Explicit
Private msLocalVar As String
Public Property Get LocalVar() As String
LocalVar = msLocalVar
End Property
Public Property Let LocalVar(sLocalVar As String)
msLocalVar = sLocalVar
End Property
Private Sub CommandButton1_Click()
Me.LocalVar = Me.LocalVar & " more strings attached"
Me.Hide
End Sub
And in a standard module
Sub ShowForm()
Dim sLocalVar As String
Dim ufUserForm1 As UserForm1
sLocalVar = "Some string"
Set ufUserForm1 = New UserForm1
ufUserForm1.LocalVar = sLocalVar 'pass in variable
ufUserForm1.Show
'This executes after the .Hide in the form
Debug.Print ufUserForm1.LocalVar
'Close out the form - previously just hidden
Unload ufUserForm1
End Sub
One way you can do this would be to declare public variables like this:
Public strvar as String
Sub Abfrage()
'Your Code
End Sub
But if you don't prefer this way, you could insert a new Excel sheet, set the properties of the new sheet to "2 - xlSheetVeryHidden" and you can write your values in the cells of that sheet and read them in from your UserForm.
So you will have no global variables, but all the values are on that sheet. Then, you can take out the values from that sheet if you need to.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With