You are confusing the concept of global variables vs. public variables. Before I start explaining, they should both be used sparingly. You also have a problem with variable declarations.
I strongly recommend to everyone that they
declare variables. Doing so prevents a lot of bug and runtime errors. In your case, you are not using Option Explicit so if you use a variable without declaring it, VBA will not tell you it's an error--it just assumes you meant to declare it, and it declares it for you with a type of Variant. I'll come back to that in a minute.
A
global variable is one that has scope and extant through an entire module. That is, it can be referenced by code anywhere in that module and its value is preserved throughout execution. (There is an exception to this called
hiding that I'm not going to get into.) A global variable must be declared at the top of a module, before the first Sub. There is no keyword for global; if it declared at the top of the module, it is global.
A
public variable is a global variable that has scope and extant through all modules. A Public variable is also global, and so must be declared at the top of a module, before the first Sub.
Your variable Pattern has been declared as Public, but you declared it inside a Sub. If you move your declaration to the top of the module, it will fix this.
Also, the place you use Pattern does not use Option Explicit. VBA does not see a declaration anywhere for Pattern that is in scope for where you are using it, so it simply creates a new variable for you and assumes it to be type Variant. This variable Pattern
is a different variable than the Pattern you declared in Sub DeclareGlobalVariables. Because this new variable that has been so conveniently created has never received a value, you get a message that it's empty.
Bookmarks