Compare Strings
By default, Visual Basic compares strings in a case-sensitive way. That means "Jeff" and "jeff" are not considered the same. You can change that by adding an Option Compare Text statement at the beginning of a module or class, as shown here:
' Ignore case when comparing
strings.
Option Compare Text
Sub CompareStrings( )
' Displays True if Option Compare is Text.
Debug.Print "Jeff" = "jeff"
End Sub
Option Compare applies to all the ways to compare string (=, Like, StrComp) throughout the module or class. You can achieve a similar result on a smaller scale by temporarily converting the strings to upper- or lowercase before comparing them:
Debug.Print LCase("Jeff") = LCase("jeff")That approach is actually more common than changing Option Compare since it allows you to use both case-sensitive and case-insensitive comparisons within a class or module.
The Like operator is similar to = in Visual Basic, except it also allows you to match patterns of characters using the comparison characters listed in Table 3-9.
Table 3-9. Pattern-matching characters
|
Use |
To match |
|---|---|
|
? |
Any single character |
|
* |
Zero or more characters |
|
# |
Any single digit |
|
|
Any single character in |
|
|
Any single character not in |
For example, the following function returns True if a passed-in argument is formatted as a Social Security number:
Function IsSSN(ssn As String) As Boolean
If ssn Like "###-##-####" Then
IsSSN = True
Else
IsSSN = False
End If
End FunctionThe Instr
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access