Control the Compiler

Visual Basic includes two instructions that tell the compiler to take special actions, as listed in Table 3-22.

Table 3-22. Visual Basic compiler directives

Directive

Use to

#Const

Define a literal constant. The compiler replaces these constants will their literal value in the compiled code.

#If...Then...#End If

Conditionally compile code based on a literal constant.

These directives are commonly used to switch between debug and release versions of code. Often, debug versions include extra statements that display output in the Immediate window. That makes it easier to locate problems while debugging, however you might not want that code to run in the released version. Rather than remove the statements manually, you can simply turn them off by changing a global setting, as shown here:

    #Const ISDEBUG = True

    Sub DemoDirectives( )
        #If ISDEBUG Then
            MsgBox "Running in Debug mode."
        #Else
            MsgBox "Running in Release mode."
        #End If
    End Sub

Changing the value of ISDEBUG changes which code runs—in fact, Visual Basic actually omits the unused code in its internal compiled version (the source code isn’t affected, however). The constant ISDEBUG isn’t really a symbol: you can’t see its value with a watch. Instead, it’s a literal value that the compiler replaces throughout your code.

Get Programming Excel with VBA and .NET now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.