Can anyone please explain the difference between declaring a variable as global or as public. Aren't they both available to the entire project including forms? Thank you.
When you Dim a variable inside a Sub or Function, it is only available to that Sub or Function. Making a variable Public makes it available to all Subs and Functions within that Module. I'm not sure if it's available to all modules; it could easily be tested.
Yes - if it's a Global variable it is available to all subs - but that seems to be the case for Public variables as well - so I am not sure of the difference.
Local: the variable is declared inside a Sub or Function, using the Dim or Static keyword and is only availible inside that procedure.
Code:
Sub myRtn()
Dim myVariable as Variant
...
Module-wide: the variable is declared at the beginning of the module with the Dim keyword. it is available ot all procedures in that module, but not to procedures in other modules
Code:
Dim myModVariable as String
Sub myFirstProceedure
...
Public - the variable is declared at the beginning of a normal module with the Public key word. It is avaliable to all procedures is all modules of that project. (Variables declared with Public in Class, Userform and Object code modules have specialized meanings.)
Code:
Public myPublicVariable as String
Sub myFirstProceedure
...
Global is not a VBA reserved word. There are no (uppercase) Global variables in VBA. "global" is a term in the meta-language of programming, not in the programming language VBA.
That's nice to know. I didn't find anything on a Global statement used for variables. I'll have to rethink how I have been declaring variables available to all subs and just to subs within a single module.
So that suggests to me that it is a reserved keyword.
The only difference I'm aware of between Global and Public is that you can't use Global when declaring variables in class modules. I don't ever use Global, although I've seen one or two other people mentioning they do use it.
We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel
Which adblocker are you using?
Disable AdBlock
Follow these easy steps to disable AdBlock
1)Click on the icon in the browser’s toolbar. 2)Click on the icon in the browser’s toolbar. 2)Click on the "Pause on this site" option.
Go back
Disable AdBlock Plus
Follow these easy steps to disable AdBlock Plus
1)Click on the icon in the browser’s toolbar. 2)Click on the toggle to disable it for "mrexcel.com".
Go back
Disable uBlock Origin
Follow these easy steps to disable uBlock Origin
1)Click on the icon in the browser’s toolbar. 2)Click on the "Power" button. 3)Click on the "Refresh" button.
Go back
Disable uBlock
Follow these easy steps to disable uBlock
1)Click on the icon in the browser’s toolbar. 2)Click on the "Power" button. 3)Click on the "Refresh" button.