75

In VB6/VBA, you can declare module-level variables outside of a specific Sub or Function method. I've used Private and Public before inside modules and understand them like so:

  • Public - visible to all code inside the module and all code outside the module, essentially making it global.
  • Private - visible only to code inside the module.

I've noticed that you can use Dim and Global as modifiers for modular variables. Are Dim and Global different from Private and Public, respectively, when used as access modifiers on modular fields? If so, how are they different?

Ben McCormack
  • 32,086
  • 48
  • 148
  • 223

1 Answers1

112

Dim and Private work the same, though the common convention is to use Private at the module level, and Dim at the Sub/Function level. Public and Global are nearly identical in their function, however Global can only be used in standard modules, whereas Public can be used in all contexts (modules, classes, controls, forms etc.) Global comes from older versions of VB and was likely kept for backwards compatibility, but has been wholly superseded by Public.

Zev Spitz
  • 13,950
  • 6
  • 64
  • 136
Joe Jordan
  • 2,372
  • 2
  • 17
  • 20
  • 1
    Thanks for your answer. Your explanation is pretty much what I had been thinking. I'm starting at a huge block of legacy code that has all four modifiers used in the declarations sections of a single module. – Ben McCormack Sep 28 '10 at 18:32
  • 4
    Global variables keep theit value after execution. – Kiril Mar 14 '15 at 16:10
  • 14
    Comparing your comments against the online help for Excel 2010 reveals a couple of very fine points: "Variables declared using the Public statement are available to all procedures in all modules in all applications unless Option Private Module is in effect; in which case, the variables are public only within the project in which they reside. Moreover, caution: The Public statement can't be used in a class module to declare a fixed-length string variable. Since both of the above are obscure use cases, neither is likely to be a practical concern. Nevertheless, in the interest of completeness. – David A. Gray Sep 19 '15 at 22:10
  • 3
    Although the question only concerned module-level declarations, for the sake of completeness (and for newbies) it's worth mentioning explicitly that `Private` and `Public` are not even allowed inside procedures. The [official documentation](https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/private-statement) of the `Private` statement seems to have a typo in this regard (it's almost identical to and probably(?) copied from the documentation for the `Dim` statement): " When you use the Private statement in [sic!] a procedure..." – Egalth Oct 11 '18 at 10:41
  • 1
    Is there documentation of the deprecation of `global` in favor of `public`? – NewSites Oct 01 '21 at 12:10