StrComp Function |
Yes
StrComp(string1, string2[, compare])
string1
Use: Required
Data Type: String
Any string expression
string2
Use: Required
Data Type: String
Any string expression
compare
Use: Optional
Data Type: Integer constant
The type of string comparison to perform.
A Variant of subtype Integer.
Determines whether two strings are equal and, if not, which of two strings has the greater value.
The following intrinsic constants are available to use as the settings for the compare argument:
Constant | Value | Comparison to perform |
---|---|---|
vbBinaryCompare | 0 | Binary (default) |
vbTextCompare | 1 | Textual |
vbDatabase | 2 | Database (Microsoft Access only) |
If compare isn't specified, the setting of Option Compare (if present) determines the type of comparison performed.
This table describes the possible return values from the StrComp function:
Scenario | Return Value |
---|---|
string1 < string2 | –1 |
string1 = string2 | 0 |
string1 > string2 | 1 |
string1 or string2 is Null | Null |
If you just need to know if string1 is greater than string2 (or vice versa), couldn't you simply use the < or > comparison operators? When you're dealing with strings of characters, Visual Basic sees each character as a number. Simply using the comparison operators therefore compares the numerical value of one string with the other. Take this scenario:
Dim sString1 As String Dim sString2 As String sString1 = "hello world" sString2 = "HELLO WORLD"
Subjectively, because of the significance of uppercase letters in text, we'd probably say that sString2 is greater than sString1. But Visual Basic sees these strings as a series of Unicode numbers, and because uppercase characters have a lower Unicode number than lowercase numbers, the lowercase string (sString1) is greater.
This is exactly how the default StrComp option vbBinaryCompare operates—comparing the Unicode numbers of each string at binary level. However, the vbTextCompare option effectively equalizes the case of both strings prior to conducting the comparison; vbTextCompare looks only for differences in the character. You could think of vbTextCompare as representing:
If UCase(sString1) < UCase(sString2) Then '-1 ElseIf UCase(sString1) = UCase(sString2) Then '0 Else '1 End If
Even performing a simple single comparison like:
If UCase(sString1) < UCase(sString2) Then
shows a performance hit of about 30% over the much more elegant and efficient StrComp function call:
If StrComp(sString1,sString2, vbTextCompare) = -1 Then
The former version, though, is easier to read and makes the code self-documenting.