Membership operators check if a value is in a specified sequence. They return True if the value is present, otherwise False.
【Excel VBA】
Excel VBA uses the Like operator to check if a string matches a pattern (using wildcards). For example, check if a string is a digit:
Sub Test5()
Debug.Print "3" Like "[0-9]" ' Is it a digit?
Debug.Print "F" Like "[a-zA-Z]" ' Is it a letter?
Debug.Print "好" Like "[一-龥]" ' Is it a Chinese character?
Debug.Print "adefb" Like "a*b" ' Pattern "a*b": any characters between 'a' and 'b'
Debug.Print "awb" Like "a?b" ' Pattern "a?b": exactly one character between 'a' and 'b'
End Sub
Running the procedure outputs True in the Immediate Window.
Chapter 6 will introduce the InStr function, which checks if a substring exists in another string and returns the position of the first occurrence (0 if not found). For example, find "VBA" in "Hello,VBA!":
Sub Test6()
Dim intI As Integer
intI = InStr("Hello,VBA!", "VBA") ' Find "VBA"
Debug.Print intI ' Output: 7(position of "VBA")
End Sub
【Python】
Common membership operators in Python are in and not in (Table 3-8).
Table 3-8 Membership Operators in Python
Examples:
>>> 1 in [1, 2, 3] # Is 1 in the list?
True
>>> 'abc' in 'wofabcmn' # Is 'abc' in the string?
True
For the wildcard effects of Excel VBA’s Like operator, Python uses regular expressions (not covered here).