VBA: Have Option Explicit be Automatically Added


VBA allows you to adopt a few lazy habits that can come back to haunt you later on. One of these is not needing to declare your variables prior to using them. Since VBA requires variables to have a type this leads to possible type confusion (you attempt to store the wrong type of value into a variable) and code that is more difficult to read.

Adding Option Explicit to the top of your modules forces you to declare your variables (the IDE will prompt you when you forget). You can set-up the IDE to automatically add this option so you don’t forget.

In the VBA IDE go to Tools > Options

Ensure that Require Variable Declaration is checked. All new workbooks and modules will have Option Explicit added.

Note: Your existing workbooks will not have Option Explicit added automatically. You will need to add it in manually (and fix up any missing declarations).