3 LIKE what?
VBA (and most implementations of BASIC from Microsoft) offers an operator called LIKE. Unlke the equal operator
(=), the LIKE operator does not look for an exact match. Instead, it checks to see if a string fits a pattern
description.
This makes the LIKE operator quite useful. For example, if PostalCodeText is a text box in a form for entering postal
code, the following code can validate it:
If Not (PostalCodeText.Value LIKE "[A-Z]#[A-Z] #[A-Z]#") Then
MsgBox("The postal code is invalid")
Cancel = True
End If
Let us explain the first line of this code a little more:
- Not
This is logical negation.
- PostalCodeText
This is the text box being referenced.
- .
We are accessing a property of the text box.
- Value
Access the value of the text box.
- LIKE
Use the “like” operator for pattern matching.
- "[A-Z]#[A-Z] #[A-Z]#"
This is the pattern to be matched. In this pattern, [A-Z] (you must use square bracket) means a character
that is in the range of upper case “A” to upper case “Z”. The single pound symbol (#) means a character that
is a digit (0 to 9). Note that the space character is also required in this pattern.
Let us now take a closer look at what can be specified in a pattern.