Visual Basic Language Reference  

StrComp Function

Returns -1, 0, or 1, based on the result of a string comparison.

Public Shared Function StrComp( _
   ByVal String1 As String, _
   ByVal String2 As String, _
   <Microsoft.VisualBasic.OptionCompareAttribute> _
   Optional ByVal Compare As Microsoft.VisualBasic.CompareMethod _
) As Integer

Parameters

String1
Required. Any valid String expression.
String2
Required. Any valid String expression.
Compare
Optional. Specifies the type of string comparison. If compare is omitted, the Option Compare setting determines the type of comparison.

Settings

The Compare argument settings are:

Constant Description
Binary Performs a binary comparison, based on a sort order derived from the internal binary representations of the characters.
Text Performs a text comparison, based on a case-insensitive text sort order determined by your system's LocaleID value.

Return Values

The StrComp function has the following return values:

If StrComp returns
String1 sorts ahead of String2 -1
String1 is equal to String2 0
String1 sorts after String2 1

Exceptions/Errors

Exception type Error number Condition
ArgumentException 5 Compare value is invalid .

Remarks

The strings are compared by alphanumeric sort values begining with the first character. For further information on binary comparisons, textual comparisons, and sort order, see Option Compare Statement.

Example

This example uses the StrComp function to return the results of a string comparison. If the third argument is omitted, a binary comparison is performed.

Dim MyStr1, MyStr2 As String
Dim MyComp As Integer
MyStr1 = "ABCD" 
MyStr2 = "abcd"   ' Defines variables.
' The two strings sort equally. Returns 0
MyComp = StrComp(MyStr1, MyStr2, CompareMethod.Text)
' MyStr1 sorts after MyStr2. Returns -1.
MyComp = StrComp(MyStr1, MyStr2, CompareMethod.Binary)
' MyStr2 sorts before MyStr1. Returns 1.
MyComp = StrComp(MyStr2, MyStr1)

See Also

InStr Function | ArgumentException