VBA 通配符
本教程將演示如何在 VBA 中使用通配符。
通配符用於所有編程語言和數據庫應用程序,如 SQL Server。通配符可以定義為用於替換文本字符串中的一個或多個字符的符號。例如,這個文本字符串 - “mo*” - 將找到單詞 mom、mouse、moose、mommy 等;而這個文本字符串“mo?” 只會找到單詞 mom 作為通配符?只替換一個字符。
我們將通配符與Like 運算符一起使用,它是VBA Regex的更簡單替代方案。
在 VBA 中使用 Asterix (*) 通配符
Asterix 通配符替換VBA 字符串中的一個或多個字符。
讓我們看一下Excel中的以下單元格區域:

通過在我們的 VBA 代碼中使用 Asterix 通配符,我們可以找到所有以“M”開頭的名字並將文本的顏色更改為紅色。
|
1
2
3
4
5
6
7
8
|
Sub
CheckForM
(
)
Dim
x
As
Integer
For
x=
3
To
8
If
Range
(
"B"&
x
)
.
Value
Like
"M*"
Then
Range
(
"B"&
x
)
.
Font
.
Color=
vbRed
End
If
Next
x
End
Sub
|
因此,我們遍歷該范圍並找到所有以字母 M 開頭的名字,因為我們的通配符字符串是“ M* ”
運行上述代碼的結果如下所示。

如果我們使用通配符字符串“Ma*”——那么只有 B3 和 B4 中的名字會改變。
在 VBA 中使用問號 (?) 通配符
問號將替換 VBA 字符串中的單個字符。
考慮以下數據:

我們可以使用通配符字符串“?im”來查找任何以“im”結尾的名字
|
1
2
3
4
5
6
7
8
|
Sub
CheckForIM
(
)
Dim
x
As
Integer
For
x=
3
To
8
If
Range
(
"B"&
x
)
.
Value
Like
"?im"
Then
Range
(
"B"&
x
)
.
Font
.
Color=
vbRed
End
If
Next
x
End
Sub
|
運行此代碼的結果如下所示:

使用 [char list] 作為通配符
The example above can be modified slightly to allow us to use the question mark, in addition to a character list of allowed characters. The wildcard string can therefore be amended to “?[e-i]m” where the first character can be anything, the second character has to be a character between e and i and the last letter has to be the character “m”. Only 3 characters are allowed.
|
1
2
3
4
5
6
7
8
|
Sub
CharListTest
(
)
Dim
x
As
Integer
For
x=
3
To
8
If
Range
(
"B"&
x
)
.
Value
Like
"?[e-i]m"
Then
Range
(
"B"&
x
)
.
Font
.
Color=
vbRed
End
If
Next
x
End
Sub
|
The result of this code would be:
Using the hash (#) Wildcard in VBA
The hash (#) wildcard replaces a single digit in a VBA string. We can match between 0 to 9.
|
1
2
3
4
5
6
7
8
9
10
|
Sub
CheckForNumber
(
)
Dim
x
As
Integer
,
y
As
Integer
For
x=
3
To
8
For
y=
2
To
5
If
ActiveSheet
.
Cells
(
x
,
y
)
Like
"##"
Then
ActiveSheet
.
Cells
(
x
,
y
)
.
Font
.
Color=
vbRed
End
If
Next
y
Next
x
End
Sub
|
The code above will loop through all the cells in the Range (“B3:E8”) and will change the color of the text in a cell to RED if a double-digit number is found in that cell.

In the example below, the code will only change the number if the last number is a 9.
|
1
2
3
4
5
6
7
8
9
10
|
Sub
CheckFor9
(
)
Dim
x
As
Integer
,
y
As
Integer
For
x=
3
To
8
For
y=
2
To
5
If
ActiveSheet
.
Cells
(
x
,
y
)
Like
"#9"
Then
ActiveSheet
.
Cells
(
x
,
y
)
.
Font
.
Color=
vbRed
End
If
Next
y
Next
x
End
Sub
|


