Skip to main content

StrComp

Returns a value indicating the result of a string comparison.

Synopsis

StrComp(string1,string2[,compare])

Arguments

string1 Any valid string expression.
string2 Any valid string expression.
compare Optional — Numeric value indicating the kind of comparison to use when evaluating strings. If omitted, a binary comparison is performed. See Description section for values.

Description

The StrComp function compares two strings character-by-character and returns a value when the first non-matching character is encountered, or when the end of the string has been encountered. StrComp returns one of the following values:

  • 0 if the two strings are identical, or if compare=1 and the strings differ only in the case of letters.

  • 1 if string1 contains a non-matching character that has a higher ANSI character code value than the corresponding character in string2. If compare=1 letters that differ in case are treated as identical. If string1 is longer than string2, StrComp returns 1.

  • -1 if string1 contains a non-matching character that has a lower ANSI character code value than the corresponding character in string2. If compare=1 letters that differ in case are treated as identical. If string1 is shorter than string2, StrComp returns -1.

The compare argument can have the following values:

Constant Value Description
vbBinaryCompare 0 Perform a binary comparison. This is the default.
vbTextCompare 1 Perform a textual comparison. Uppercase and lowercase letters are equivalent.

The StrComp function has the following return values:

If StrComp Returns
string1 is less than string2 -1
string1 is equal to string2 0
string1 is greater than string2 1

Examples

The following example compares two strings that differ only in the case of letters:

Println "default:  ",StrComp("abcd","ABCD")    ' Returns 1
Println "binary:   ",StrComp("abcd","ABCD",0)  ' Returns 1
Println "textual:  ",StrComp("abcd","ABCD",1)  ' Returns 0
Println "default:  ",StrComp("ABCD","abcd")    ' Returns -1
Println "binary:   ",StrComp("ABCD","abcd",0)  ' Returns -1
Println "textual:  ",StrComp("ABCD","abcd",1)  ' Returns 0

The following example compares two strings that differ only in length:

Println "binary:  ",StrComp("abcde","abcd",0)  ' Returns 1
Println "textual: ",StrComp("abcde","abcd",1)  ' Returns 1
Println "binary:  ",StrComp("abcd","abcde",0)  ' Returns -1
Println "textual: ",StrComp("abcd","abcde",1)  ' Returns -1
FeedbackOpens in a new tab