Variable public VBA refers to a variable declared with the Public keyword in a standard module, making it accessible from any procedure in any module of the same workbook. You declare it once at the top of a module (outside any procedure) and then read or change it from any other macro, user form, or even from the Immediate window.
What Does “Public” Actually Do in VBA?
In VBA, a variable’s scope controls where it can be seen. A variable declared inside a procedure (with Dim) is local—only that procedure can use it. A variable declared with Private at the top of a module is visible to all procedures in that same module but not to other modules. A variable declared with Public at the top of a standard module is visible to the entire project: all modules, all user forms, and even other workbooks if you reference the project.
Here’s a minimal example:
' Module1 (standard module)
Public UserName As String
Sub SetName()
UserName = "Alex"
End Sub
Sub ShowName()
MsgBox UserName
End Sub
Run SetName first, then ShowName—the message box displays “Alex”. The variable UserName persists as long as the VBA project is running (i.e., the workbook is open).
Where to Declare a Public Variable
You must place the Public statement at the top of a module, in the Declarations section, before any Sub or Function. It cannot be inside a procedure. Standard modules (the ones you insert via Insert > Module) are the usual home for public variables. You can also declare them in class modules, but then they are only public to instances of that class—not the whole project.
Important: If you declare a Public variable in a user form module or a sheet module (like Sheet1), it behaves like a Private variable—it is not accessible from other modules without a qualifier. For true project-wide access, use a standard module.
Public vs. Global vs. Private
VBA also has a Global keyword, which is identical to Public in a standard module. Many older tutorials use Global, but Public is the modern, preferred choice. The difference between Public and Private is exactly the scope described above. Here’s a quick comparison:
- Dim inside a procedure: local, only that procedure.
- Private at module top: accessible to all procedures in that module, not to other modules.
- Public at module top: accessible to all procedures in the whole project.
- Global: same as Public, but considered outdated.
If you declare a Public variable in a standard module, you can also refer to it from another module using the module name, e.g., Module1.UserName. This is optional but can avoid naming conflicts.
How to Use a Public Variable Across Modules
Suppose you have two standard modules: Module1 and Module2. In Module1 you declare:
Public ConfigPath As String
Then in Module2 you can write:
Sub LoadConfig()
ConfigPath = "C:\Settings\config.ini"
' ... read file ...
End Sub
Because ConfigPath is public, Module2 can assign and read it without any extra syntax. If you wanted to be explicit, you could write Module1.ConfigPath.
Common Problems and Pitfalls
The most frequent issue with public variables is that they lose their value when you reset the VBA project. If you click the Reset button (the square icon) in the VBA editor, or if an unhandled error stops execution, all module-level variables are cleared. This can cause “empty” or Nothing values in later procedures. To avoid this, always re-initialize public variables at the start of your main procedure or use a Workbook_Open event to set defaults.
Another common problem is name collisions. If you have a public variable named Count and also a procedure-level variable named Count, the local one shadows the public one. This leads to confusing bugs. Use a prefix like g_ (for global) to distinguish, e.g., g_UserName.
Finally, public variables are not saved when the workbook is closed. If you need to persist a value between sessions, store it in a cell, a custom document property, or in the Windows registry.
Public Variables vs. Public Constants vs. Public Functions
You can also declare Public Const for constants that never change, like Public Const MaxRows As Long = 1048576. These are read-only and can be used anywhere. Public functions are different: they are procedures that return a value and can be called from any module, but they do not store state. A public variable is a storage location; a public function is a calculation. For example:
Public Function GetAppName() As String
GetAppName = "Excel Helper"
End Function
You can call GetAppName from any module, but it does not remember anything between calls. If you need a value that persists, use a variable.
Frequently Asked Questions
Can I declare a public variable in a worksheet module?
Yes, but it won’t be truly public. In a sheet module (e.g., Sheet1), a variable declared as Public is only accessible from within that sheet’s code module, and from other modules you must refer to it as Sheet1.VariableName. It is not automatically visible project-wide. For global access, put it in a standard module.
Do public variables reset when I press the Stop button?
Yes. Clicking the Reset (stop) button in the VBA editor clears all module-level variables, including public ones. Also, if your code hits an unhandled error and you choose “End”, the project resets. To preserve values during debugging, avoid resetting or use a static variable in a procedure (but that only persists within that procedure).
Can I use a public variable in a UserForm?
Yes. If you declare a public variable in a standard module, you can read or set it from a UserForm’s code. For example, in a button click event you can write g_UserName = TextBox1.Value. The variable is accessible because the form’s code is part of the same project.
What is the difference between Public and Static?
Static is used inside a procedure to make a local variable retain its value between calls to that procedure. It is not visible outside the procedure. Public is for module-level variables that are visible everywhere. They serve different purposes: Static for a persistent counter inside one function, Public for shared data across the whole project.
How do I make a public variable available to another workbook?
If the other workbook has a reference to this workbook (via Tools > References in the VBA editor), you can access the variable using the project name, e.g., ProjectName.Module1.UserName. However, this is rarely done because it creates fragile dependencies. A better approach is to pass the value as an argument to a macro in the other workbook, or use a custom document property.
Is there a way to make a public variable constant?
Yes, use Public Const instead of Public. For example: Public Const AppVersion As String = "1.0". You cannot assign a new value to a constant at runtime. If you need a value that can change but should be protected from accidental modification, consider using a Property Get/Let in a class module.
Best Practices for Public Variables
To keep your code maintainable, follow these guidelines:
- Declare all public variables at the top of a dedicated standard module, not scattered.
- Use a prefix like
g_to make them stand out. - Initialize them in a
Workbook_Openevent or at the start of the main macro. - Minimize the number of public variables; too many global states make debugging hard.
- Consider using a
Typeor a class to group related public variables.
For example, instead of three separate public variables for user settings, define a custom type:
Public Type UserSettings
Name As String
Age As Integer
Email As String
End Type
Public CurrentUser As UserSettings
Then you can set CurrentUser.Name = "Alex" and read it anywhere. This reduces clutter and makes the data structure clear.
Alternatives to Public Variables
If you find yourself using many public variables, consider these alternatives:
- Custom document properties: store values in the workbook’s built-in properties (accessible via
ThisWorkbook.CustomDocumentProperties). They persist across sessions and can be read without VBA. - Named ranges: put values in hidden cells and give them names. This is simple and visible in the worksheet, but slower for frequent access.
- Static variables: for counters or caches used only within one procedure.
- Class modules: create an object that holds state and pass it around. This is more advanced but gives better encapsulation.
Each method has trade-offs. Public variables are the simplest for small projects, but for larger applications, a class-based approach is often cleaner.
In summary, a public variable in VBA is a project-wide storage location declared with the Public keyword in a standard module. It is easy to use, but you must be aware of reset behavior and naming conflicts. Use it sparingly and follow the best practices above to avoid bugs.
Related
- String Split in C++: Methods and Examples
- Enum in SQL: Meaning, Usage, and Alternatives
- Display a Shortcut Menu for the Main Document Area?
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- Excel VBA: Loop Through Folders and SubfoldersTo loop through folders and subfolders in Excel VBA, use the FileSystemObject with a recursive procedure, or the…
- Excel VBA: Open a Text File for Reading, Step by StepTo open a text file for reading in Excel VBA, assign a free file number, use the Open…
- Excel VBA: How to Change Cell Formats to GeneralTo change a cell’s number format to General with VBA, assign General to its NumberFormat property: Worksheets("Sheet1").Range("A1").NumberFormat =…
- Excel VBA: Fill a Formula Down to the Last Data RowTo fill a formula in B2 down through the last row that has data in column A, find…
- Excel VBA AutoFilter Multiple Fields: Examples and TipsTo filter multiple Excel fields with VBA, call AutoFilter on the same range once for each column, using…
- Excel VBA End If Statement: How to Use ItThe End If statement in Excel VBA closes an If...Then...Else block, telling the compiler where the conditional logic…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.