Excel VBA StrComp Function
VBA StrComp Function: The StrComp function in VBA compares two strings and returns an integer value displaying the result of the comparison.
Syntax
StrComp (String1, String2, [Compare])
Parameter
String1 (required)- This parameter represents the first string to be compared.
String2 (required) – This parameter represents the second the second string to be compared.
Compare (optional) - This parameter represents the type of comparison to make. The default value is vbBinaryCompare.
It can take any of the following values:
- vbBinaryCompare (default value): To perform a binary comparison
- vbTextCompare: To perform a text comparison
- vbDatabaseCompare: To perform a database comparison
Return
This function integer value displaying the result of the comparison. The returned output can be of any of the following values:
- It returns 0, if both the strings are equal.
- It returns -1, if String1 is less than String2
- It returns 1, if String1 is greater than String2.
- It returns null, if both the strings are Null
Example 1
Sub StrComp_Example1()
'Comparing the Strings (string1 and string2).
Dim str As Integer
'initializing the string 1
String1 = "Joey Jonas"
'initializing string 2
String2 = "Joey Jonas"
str = StrComp(String1, String2)
' The Integer str will return integer value 0 as both the strings are equal.
If str = 0 Then
MsgBox ("Both the strings are equal!")
Else
MsgBox ("Opps! Both the strings are unequal")
End If
End Sub
Output
Both the strings are equal!

Example 2
Sub StrComp_Example2()
Dim str As Variant, IB As Variant
'initializing with the password
Password = "panda"
Jmp:
IB = InputBox("Enter your Password")
If Password = IB Then
MsgBox ("Hello! Welcome to VBA World!")
Else
MsgBox ("Sorry! Retry the password")
GoTo Jmp
End If
End Sub
Output




