IfThen and Platform

In Visual Basic 4.0, which included both 16- and 32-bit versions, the major application of the #If...Then compiler directive was to generate separate executables for the 16- and 32-bit Windows platforms. For this purpose, VBA included two conditional compiler constants, Win16 and Win32; if one was True, the other was automatically set to False. Visual Basic 5.0 and VBA 5.0 onwards, however, support only the 32-bit Windows platforms. Consequently, the Win16 and Win32 constants are no longer supported.

Rules at a Glance

• According to the documentation, only operators (other than Is) and conditional compiler constants can be used in the expression to be evaluated. In fact, you can draw on a considerably broader range of the VBA language to

118 Chapter 7- The Language Reference evaluate a conditional compiler expression. In addition to these, you can use literals, variables, and some functions.

• Unlike the normal If...Then statement, you can't use a single-line version of the #If...Then statement.

• All conditional compiler constants used in conditional compiler expressions must be defined; otherwise, they evaluate to Empty. This, in turn, means that the conditional compiler expression evaluates to False.


#Const ccVersion = 2.5 Private oTest as Object

Sub GetCorrectObject()

#If ccVersion = 2.5 Then

Set oTest = New MyObject.MyClass #Else

Set oTest = New MyOtherObject.MyClass #End If

End Sub Programming Tips & Gotchas

• You can negate the evaluation of the expression in the #If...Then or #ElseIf...Then statements by placing the Not operator before the expression. For example, #If Not ccVersion = 5 Then forces the code after this line to be compiled in all situations where ccVersion doesn't equal 5.

• Conditional compilation helps you debug your code, as well as provide a way to create more than one version of your application. You can include code that operates only when run in debug mode. The code can be left in your final version and won't compile unless running in the debugger; therefore, you don't need to keep adding and removing code.

• That you can use a wider range of language elements without generating a compiler error doesn't necessarily mean that you should use them or that using them produces the result that you want. This applies to the use of variables in particular; the distinguishing feature of a variable (and the reason for its name) is that its value is allowed to vary at runtime. The evaluation of conditional expressions, however, occurs at compile time.

See Also

#Const Directive, Debug.Print Method, If...Then Statement

Was this article helpful?

0 0

Post a comment