Both Excel VBA and Python support string comparison using relational operators or dedicated functions.
Using Relational Operators
[Excel VBA] Relational operators (<, <=, >, >=, =, <>) compare strings character-by-character from left to right. Example:
Sub Test()
Dim strA As String, strB As String
strA = "abc"
strB = "abc123"
Debug.Print strA < strB ' True(shorter string is "smaller" if prefixes match)
End Sub
[Python] Use ==/!= (value equality), is (object identity), in/not in (substring check).
>>> a = 'abc'
>>> b = 'abc123'
>>> a == b # False(values differ)
>>> a != b # True
>>> a is b # False(different objects)
>>> 'abc' in b # True (substring exists)
>>> 'd' not in b # True (substring does not exist)
Using Functions
[Excel VBA] Use StrComp to compare strings. Returns:
-1: String1 < String2
0: String1 = String2
1: String1 > String2
Null: Either string is Null.
Syntax:
StrComp(String1, String2[, Compare])
Example:
Sub Test2()
Dim strA As String, strB As String, strC As String
Dim varComp1, varComp2, varComp3
strA = "abc"
strB = "abc123"
strC = "ABc"
varComp1 = StrComp(strA, strB) ' Case-sensitive: -1(abc < abc123)
varComp2 = StrComp(strA, strC) ' Case-sensitive: 1(abc > ABc)
varComp3 = StrComp(strA, strC, vbTextCompare) ' Case-insensitive: 0(abc = ABc)
Debug.Print varComp1, varComp2, varComp3 ' -1 1 0
End Sub
[Python] Python 3 has no direct equivalent to StrComp, but the operator module provides similar functions (Table 6-7).
Table 6-7 String Comparison Functions in operator Module
Example:
>>> class="text-secondary">import operator class="text-secondary">as op
>>> op.lt('a', 7;b') # True(a < b)
>>> op.eq('a123', 'a12b') # False(a123 ≠ a12b)
>>> op.ge('forpython', 'forvba') # False(forpython < forvba)
Other string comparison functions (Table 6-8):
Table 6-8 Additional String Comparison Functions
Examples:
>>> 'Abc123'.isalnum() # True (letters and digits)
>>> 'Abc123'.isalpha() # False (contains digits)
>>> '123123'.isdigit() # True (all digits)
>>> '123.123'.isnumeric() # False (contains '.')
>>> 'abc'.islower() # True (all lowercase)
>>> max('Abc') # 'c' (largest character)