I did a quick search on my favourite forum for details about Global vs Public in Excel VBA and didn't find much so I thought I'd add a thread for the benefit of others. While I was looking for (there isn't much!) information about this I came across Chip Pearson's awesome website yet again.
It seems the main difference between Public and Global is to do with accessing variables declared as either from within other projects. N.B. Global can only be used for variables and not procedures; excel will automatically remove Global and treat a procedure as Public
Both Public and Global variables in a standard code module will produce the same results within the project, that is, either can be accessed from anywhere (including object modules) within the project. Either can also be accessed from another project.
However ifis used at the top of the module, this restricts Public variables within that module from being "seen" by other projects while still being Public within it's own project. Global variables cannot be restricted in this way and so cannot be declared in modules that use Option Private Module. I presume it would generate a compiler error.![]()
Please Login or Register to view this content.
Global cannot be used in an object module (like Class Modules, Userforms, ThisWorkbook etc). Likely for a similar reason that it can't be used in a code module that uses Option Private Module; how code in those modules handles interaction from other projects.
A more detailed explanation can be found in the two paragraph's on Project Scope and Global Scope on Chip's website here.
Effectively it looks like Public will do everything Global can do but has added flexibility when it comes to interaction from other projects. I read somewhere else that Global and Dim come from older versions of VB and were probably only kept for backwards compatibility (and old programmers who find change challenging! lol). It seems it would make more sense to ditch them entirely as neither offer anything that Public and Private don't offer. Views?
I'd be interested if anyone knows of any other differences and for that matter any differences between Private and Dim or more specifically, when Dim can do something that Private can't. So far, the only reasonably objective uses for Private vs Dim I've found is Dim would tend to be used to declare procedure scope variables while Private would be used more to declare module scope variables. But the location of the variable declaration determines the scope, not the way the variable is declared, so this doesn't really convince me that Dim should hang around either.
Bookmarks