Hello World
Our first encouter with VBA will be to display the familiar "Hello World" message using a button.
Expand | ||
---|---|---|
| ||
|
Expand | ||
---|---|---|
| ||
Explicit vs implicit variable declaration
Expand | |||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| |||||||||||||||
Before we look at the different variable declarations, we need to establish the difference between the words explicit and implicit.
When coding in Visual Basic, you are by default not obligated to declare your variables before using them. This an example of an implicit variable declaration.
When doing so, VBA will automatically declare it as a variant type provided that the variable has not been declared before. This is a nice feature, but may cause trouble when writing larger scripts. Let's look at an example: We have already written a lot of code using the variable " MyVarMyVariable". If we were to misspell " MyVarMyVariable" with " MyvarMyVaiable" in one lineonce, VBA will think of it as a new variable, and declare it automatically, thus not informing us.
To avoid this problem, we can use the Option Explicit Statement. It ensures that all variables must be explicitly declared by using the Dim, Private, Public, ReDim or Static statements. Otherwise, it will display an error at compile time. If used, the "Option Explicit" statement must appear in a module before any procedures.
Compiling the code above will result in the following error message. |
If you want to make all your modules have the "Option Explicit" statement, without having to remember to write it yourself, follow these instructions:
- In your VBA editor, go to "Tools" → "Options".
- Tick the "Require Variable Declaration" box. Click "OK".
BibTeX Display Table |
---|