Search notes:

VBA: Conditional compilation: preprocessing the source code with #if … #end if

The VBA compiler directives #if … then and #end if allow to only compile the respective enclosed portions of source code if a certain condition is defined.
These compiler directives act similar to the #ifdef preprocessor directive in C and C++.
option explicit

sub main()

   #if VBA7 then
       debug.print "VBA7 is defined"
   #else
       debug.print "VBA7 is not defined"
   #end if

   #if     win64 then
           debug.print "win64 is defined"
   #elseif win32 then
           debug.print "win32 is defined"
   #else
           debug.print "neither win64 nor win32 is defined"
   #end if

end sub
Github repository about-VBA, path: /compiler-directives/conditional-compilation/if-then-else.bas
It's possible to define values to be queried with the #const directive.

«Commenting out» sections of code

#if 0 then … #end if allows to quickly «comment out» a section of code:
option explicit

sub main() ' {

    debug.print "one"

#if 0 then

    debug.print "two"
    debug.print "three"
    debug.print "four"

#end if

    debug.print "five"

end sub ' }
Github repository about-VBA, path: /compiler-directives/conditional-compilation/if-0.bas
The «commented» section of the code can be included again by changing the 0 to 1.

Nesting directives

It's possible to nest #if … #end if statements:
option explicit

sub main() ' {

     debug.print "A"

#if 0 then

     debug.print "B"

  #if 0 then
     debug.print "C"
  #else
     debug.print "D"
  #end if

     debug.print "E"

#else

  #if 1 then
     debug.print "F"
  #else
     debug.print "G"
  #end if

     debug.print "H"

#end if

     debug.print "I"

end sub ' }
'
' A
' F
' H
' I
Github repository about-VBA, path: /compiler-directives/conditional-compilation/nested.vb

See also

The predefined win64, win32 and win16 and vba6 and vba7 compiler directive constants.
The VBA if statement
Visual Basic for Application

Index