String Comparisons
- Last UpdatedJul 18, 2023
- 1 minute read
VBA compares ANSI values of characters when comparing strings. For example, the character capital 'A' has the ANSI value of 65, and the character lowercase 'a' has the ANSI value of 97. For a listing of ANSI characters values, see ASCII/ANSI Character Code Listings.
You can use VBA relational operators (less than, greater than, equal to, not equal to, and so on) to compare string variables. All relational operators return either true or false.
With comparisons made using relational operators, the result depends on the option compare string-comparison option setting of the VBA file. Consider the following example:
"vba" > "VBA"
If the file Option string-comparison setting is Option Compare Binary (or not set at all), the comparison returns true. VBA compares the binary (ANSI) values for each corresponding position in the string until it finds two that differ. In this example, the lowercase letter "v" corresponds to the ANSI value 118, while the uppercase letter "V" corresponds to the ANSI value 86. Because 118 is greater than 86, the comparison returns true.
If the file Option string-comparison setting is Option Compare Text, "vba" > "VBA" returns false, because the strings are equivalent apart from case.
The built-in VBA StrComp() Function returns a variant containing a value representing the result of the comparison of two strings. It has an optional third argument Comp which can override the file Option string-comparison setting.