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
|