Understanding Conditional Compilation
This content is no longer actively maintained. It is provided as is, for anyone who may still be using these technologies, with no warranties or claims of accuracy with regard to the most recent product version or service release.
You can use conditional compilation to selectively include blocks of debugging code by testing for the value of a conditional compilation constant. If the constant is True, the debugging code is included. To do this, you specify a conditional compilation constant by using the #Const directive. You then test for the value of this constant within a procedure by using the #If…Then…#Else directive within a procedure. For example, the following procedure uses the value of the FLAG_DEBUG conditional compilation constant to determine if the conditional constant is set to True. If the constant is set to True, the Assert method of the Debug object is used to test the validity of the procedure's input parameters. For example:
Sub OutputString(strMessage As String, _
Optional intOutputType As Integer = 0)
Dim intFileNum As Integer
#If FLAG_DEBUG = True Then
' Test validity of strMessage.
Debug.Assert Len(strMessage) > 0
' Test validity of intOutputType.
Debug.Assert intOutputType >= 0 and intOutputType <= 3
Stop
#End If
Select Case intOutputType
Case 0
.
.
.
End Sub
Using conditional compilation is really a shortcut for commenting out entire blocks of code depending on a global setting. Without the ability to use the constant as a flag to direct program flow, you would have to litter your code with commented-out calls to alternative procedures. If you always use conditional compilation constants to test alternative procedures, then you have an easy way to turn on and off calls to the designated procedures and an easy way to find the code that you ultimately decide to remove. The cost of using this technique is that you must give a great deal of thought to how your code is constructed and called. Although this might mean a little more work, it results in manageable, maintainable, and reusable code.
See Also
Writing Error-Free Code | Design-Time Tools | Run-Time Tools | Script Debugging Tools | Using Assertions | Creating Custom Assertions | Handling Errors | Writing Solid Code