Case-Sensitive string comparisons
Today’s guest blogger is Michael Groh, co-author of the popular Access 2007 Bible.
The VBA language is not, by default, case-sensitive. A statement such as
CBool("XYZ" = "xyz")
will always return True. You might come across this issue in cases such as the following:
If strOne = strTwo Then
' Perform some operation here
End If
Consider what happens if it's important to know that the strings differ only by case. By default, VBA will never report a difference in the strings based only on the case applied to the string variables.
One easy fix is to use the InStrB ("in string byte") function, which considers the strings based on byte value (where "x" is different than "X"). By contrast, the InStr function considers just character value ("x" is the same as "X").
The transformed If statement becomes:
If CBool(InStrB(strOne, strTwo)) Then...
This statement takes the output of InStrB() and converting it to a Boolean (True or False) expression. When InStrB returns 0 (no match found), CBool converts the expression's value to False. If InStrB finds the strings match (by case and by character) the expression evaluates to True.
You'll find that using the InStrB() function is much faster and easier than writing a VBA function that parses each string and does a binary or ASCII comparison on each character in both strings.
Get your favorite Power Tip on the blog! Send it to Mike and Chris at accpower@microsoft.com.