Thursday, September 15, 2022

How to force variables declaration before start VBA code?

Variables declaration is very importance before start writing any code in VBA because:

  • More organize whenever code is getting complicated or longer otherwise we get lost somewhere and stuck (Normally variables declaration is on top of any procedure).
  • Computer memory limitation slowing down the processing because without declaration default is set as variant.
  • More easy to write especially on object example Workbook, Worksheet and etc. This is because we can use Tools tip suggestion whenever we key in dot after variables.
  • Simplify code because we only assigned this variables one time but can be use many time. For example:
    Dim StrPath As String
    StrPath = "C:\Users\UserName\Desktop\MyFiles.xlxs"
    We use StrPath instead of full path and can be repeated many time.

To force declaration either Dim, Private, Public, ReDim, or Static statements, we use Option Explicit statement on top of module before any procedures. Variables without declaration will be warn as below.


Microsoft Visual Basic for Applications: Compile error: Variable not defined

To set as default whenever module inserted:

  • Under Visual Basic Editor Click Tools follow by Option.


  • Under Options window select Editor Tab and tick Require Variable Declaration.


  • Click OK. Done

Note: Every time Module inserted "Option Explicit" always on top.

Microsoft Reference - Option Explicit Statement

Practice makes perfect. Thank You.

No comments:

Post a Comment