Creating a global Compilation Directive to optionally compile code

Status
Not open for further replies.

Banana

split with a cherry atop.
Local time
Yesterday, 18:27
Joined
Sep 1, 2005
Messages
6,318
For those who are unaware of what 'compiler directive' is, there are two special statements that can be used in Visual Basic for Application to control what block of codes actually get compiled or skipped over.

The #Const statement declares a variable that the compiler will use in determining which block of codes we will compile.
Code:
#Const DebugVersion = 1

The #If...#Then statement then puts the #Const to test:
Code:
#If DebugVersion = 1 Then
   'Execute some debugging code
#End If

Note: You can use #Else and #ElseIf as well if you need more conditions.

This is a useful way to write debugging codes or platform-specific code without bloating your application when you distribute because you only need to change the Const to the appropriate value and certain blocks of code will be compiled (or not at all), so there is no performance penalty as would be the case if we simply used a simple If/Then conditional because in that case, it's evaluated at run-time and will be evaluated *every* time it is called whereas the #If/#Then is evaluated at compile-time and therefore exactly once prior to distribution.

But one sticking point that stopped me from using it was the fact that #Const was always a private variable; there was no way to declare it globally; one had to put it in each module where it was needed, which is just unnecessary work.

Reading the help file, it makes cryptic references to user interface. By luck, I was able to figure out that there IS a way to create a global #Const statement. The thing is it can't be written in code but only through user interface, which is the project's properties.

To get to that dialog, we need to click Tools -> <your database name> Properties

It should open a dialog. Near the bottom, there is a field "Conditional Compilation Arguments". Using the above example, we'd omit the #Const and put in "DebugVersion=1" in that field. Press OK, then you now have a global #Const to apply to all modules.

There's one more catch: You can't use a string but only integer for that field. Not that big setback, and it's not exactly discoverable, but at least we truly get to change it in only one place.
 
Status
Not open for further replies.

Users who are viewing this thread

Back
Top Bottom