Global Variables using User Forms

  • Thread starter Thread starter Steve
  • Start date Start date
S

Steve

Is there a way to set global variables so I can use them
in while I am coding in a user form. Right now I am
setting the variable up under the workbook and it works in
any worksheet, however when I try to access that data in a
user form opened from the worksheet, it does not work.
Any Ideas?

Thanks,
Steve
 
This code belongs in the Workbook module:

Public vTest As String
Sub The_Test()
vTest = "Can you see me?"
UserForm1.Show
End Sub

This code belongs in the UserForm1 module:

Private Sub UserForm_Initialize()
UserForm1.Caption = ThisWorkbook.vTest
End Sub

You need to publicly declare it at the module level, and
in the form - qualify the module with the variable. So to
access functions and variables from a UserForm, explicitly
qualify with "ThisWorkbook" or whatever module it is.

HTH.

-Brad
 
If just using it within you project,
better in my opinion would be to declare it in a general module

General Module: (Insert => Module in the VBE)
Public vTest as String

ThisWorkbook module
Sub The_Test()
vTest = "Can you see me?"
UserForm1.Show
End Sub

Userform Module
Private Sub UserForm_Initialize()
UserForm1.Caption = vTest
End Sub


Then you don't have to worry about qualifying it and all elements of the
Project can see it (without qualifying it)
 
Class modules (worksheet modules, userform module, thisworkbook module and
class modules) are private by default.
 
Back
Top