In VBA for Access, how do I make a global variable that I can access and change anywhere?
-
Add a Module, at the top `public variablename as datatype_you_want` – Alex K. Sep 22 '16 at 12:48
-
1just to throw in that the more code lines a project has the less `Public` variables should be used in it – user3598756 Sep 22 '16 at 12:51
1 Answers
You can declare a variable at Global scope by declaring it in a Standard Module or a predeclared class module such as a Worksheet, UserForm or PreDeclared class, using the Public
keyword:
Public myVar As String
You can also declare a Global variable using the now deprecated, but still valid Global
syntax, which is functionally the same as Public
Global myVar As String
But note that declaring a variable with Public
or Global
will make the variable accessible across your entire project AND to any project that refers to that project, and even if your project is protected, a user could still query the variable from the Immediate window.
If you must have a variable that is available across your project, but only that project, then you should declare the variable in a standard module, and include an Option Private Module
statement to make the module private to the project, but its variables as Public to the project only.
Option Private Module
Public myVar As String

- 9,352
- 2
- 29
- 60
-
Is there documentation of the deprecation of `global` in favor of `public`? – NewSites Oct 01 '21 at 12:12