Question

I was under the impression that it was always best to write:

If Not X = Y then

then

If X <> Y then

but I'm not sure where I did I get this idea:-).

Is there a best? Why do we have two way to do the same thing anyways?

tks!

Was it helpful?

Solution

Readability is most important.

The second seems more natural to me. It seems misleading to use the equal sign and then adding the Not to it.

The Not IMHO is best used with boolean functions like IsNumeric(...) which lends itself to a more natural reading of the code, E.g.,

If Not IsNumeric(myNumberString) Then

And, I personally prefer using Not to = False for Boolean tests. E.g., I like...

If bFlag1 Then
If Not bFlag2 Then

...more than...

If bFlag1 = True Then ' <-- (This is totally redundant) = True
If bFlag2 = False Then
If a <> b = True Then ' <-- please don't ever do this

OTHER TIPS

The first option is to be avoided as confusing. Someone might think that you meant to write If (Not X) = Y Then.

Why do we have two ways? Because... how could you prevent it? It's a natural consequence of having the three operators =, <>, and Not.

Besides style and readabilty there is a little difference:

Not is a logical operator and <> is a relational operator and logical and bitwise operators have a lower precedence than other arithmetic and relational operators (see here).

Furthermore the Not operator can be overloaded, I think this is not possible for relational operators in VBA.

I think that If X <> Y Then... is more expressive (but this is a matter of preference). Also it might be more efficient in terms of condition evaluation, since If Not X = Y Then... needs two operations (evaluating the equality and negating the result) rather than one. But, with some code optimisation behind the scene, who knows what actually happens?...

However, there are cases when is impossible to avoid the negated condition; for example the Is operator does not have a negated form (like Isn_t or something), so in this case you need to say If Not X Is Y Then...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top