Microsoft Project VBA: Option Explicit vs Implicit

After coding quite a while in Microsoft Project using VBA I’ve noticed that many people don’t use Option Explicit at the top of the modules they are creating code in Microsoft Project.  I see it more often used when I see Microsoft Excel code.  It’s important to understand that using Option Explicit is beneficial when coding.

When writing VBA the default is to read variables implicitly.  This means that if you want to create new variables you can create them on the fly without having to declare them.  That sounds wonderful until you misspell your variable and VBA reads it as a new variable.  Therefore, I find it more useful to declare in your code that you will explicitly declare each of your variables and if they are not explicitly declared, then you will automatically get an error.

To better understand this issue let’s start by looking at some simple code.  Say you have the following code with only one variable myNum.  You find yourself typing really fast and misspell myNum and write mNum:

Sub explicitTest()
Dim myNum As Integer

myNum = 25

ActiveProject.Tasks(1).Text1 = myNum

mNum = 80

ActiveProject.Tasks(1).Text1 = mNum

End Sub

Result:

codeSnippetText1

You run the code and there is nothing to tell you that now you have introduced a new variable without even knowing.  What if you make the same mistake later in the code and try to use mNum and you get in return the wrong number?  It becomes difficult to trace this type of error back to where it was introduced.

Here is where Option Explicit is very important.  You try the same code but with Option Explicit at the top of the module.

Option Explicit

Sub explicitTest()
Dim myNum As Integer

myNum = 25

ActiveProject.Tasks(1).Text1 = myNum

mNum = 80

ActiveProject.Tasks(2).Text1 = mNum

End Sub

Result:

errorVariableNotdefined

The error was caught as soon as the code was run.  Since it wasn’t defined as a Dim you will get an error.  This is good because you will avoid introducing potential bugs into your code that are hard to trace.  If you did mean to introduce a new variable, then when getting this error you will know you need to go back and declare this new variable before continuing.  This gives you greater control of everything happening within your code.

You can automatically add it to all your new code.  Remember, this will NOT add it to your existing code, you will have to make sure to add it manually at the top.

To add it automatically to your code every time you are start new code you can do the following:

  • Make sure you are in the Visual Basic Editor (VBE)
  • Go to Tools > Options
  • Once the Options pop-up window comes up check off the “Require Variable Declaration”

optionsExplicit.png

  • Click Okay

There!  you will not have to worry about adding this to all your new code.



Leave a comment