Greg Maxey said:
In this example, is there technical reason to use example 1A & B over
example 2 A & B. Does it make any difference?
Sub BestPractice()
Dim bPractice As Boolean
bPractice = True
If bPractice Then MsgBox "Example 1A"
If bPractice = True Then MsgBox "Example 2A"
The first option above is better. The Then clause is executed if the overall
expression evaluates to True. Since bPractice is boolean, bPractice=True is
always thge same is bPractice.
However, note what others have said about impicit conversions to boolean If
you have this instead
Sub BestPractice()
Dim iPractice As Long
iPractice = 5
If iPractice Then MsgBox "Example 1A"
If iPractice = True Then MsgBox "Example 2A"
The Then clause of the first line will execute if iPractice has any value
other than 0, because when a Long is connverted to a Boolean, 0 becomes
False and all other values convert to True
The Then clause of the second line will only execute if iPractice is -1.
That is because True is converted to a Long whose value is -1 before the
comparison is made with iPractice. The entire expression only evaluates to
True if the two values are equal.
bPractice = False
If Not bPractice Then MsgBox "Example 1B"
If bPractice = False Then MsgBox "Example 2B"
Much the same considerations apply here.
The overall lesson here is that you need to be aware of what is going on
when type conversions are happening. To ensure that type conversions happen
in the way that you want and expect, you can use the CInt, CLng, CBool and
similar type conversion functions to force an explicit type conversion on an
expression.
Thus you get different results from the following
If CBool(iPractice) = True Then MsgBox "Example 2A"
If iPractice = CLng(True) Then MsgBox "Example 2A"
--
Regards
Jonathan West - Word MVP
www.intelligentdocuments.co.uk
Please reply to the newsgroup
Keep your VBA code safe, sign the ClassicVB petition
www.classicvb.org