vbavb6scopeaccess-modifiers

What is the difference between Dim, Global, Public, and Private as Modular Field Access Modifiers?


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:

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?


Solution

  • 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 kept for backwards compatibility, but has been wholly superseded by Public.

    [Global] and the optional Shared keyword (section 3.3.5.1) provides syntactic compatibility with other dialects of the Basic language and/or historic versions of VBA."

    Source: VBA Specification