VBA like和通配符
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
|
SubCheckForM()
DimxAsInteger
Forx=3To8
IfRange("B"&x).Value Like"M*"Then
Range("B"&x).Font.Color=vbRed
EndIf
Nextx
EndSub
|
因此,我们遍历该范围并找到所有以字母 M 开头的名字,因为我们的通配符字符串是“ M* ”
运行上述代码的结果如下所示。
如果我们使用通配符字符串“Ma*”——那么只有 B3 和 B4 中的名字会改变。
在 VBA 中使用问号 (?) 通配符
问号将替换 VBA 字符串中的单个字符。
考虑以下数据:
我们可以使用通配符字符串“?im”来查找任何以“im”结尾的名字
1
2
3
4
5
6
7
8
|
SubCheckForIM()
DimxAsInteger
Forx=3To8
IfRange("B"&x).Value Like"?im"Then
Range("B"&x).Font.Color=vbRed
EndIf
Nextx
EndSub
|
运行此代码的结果如下所示:
使用 [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
|
SubCharListTest()
DimxAsInteger
Forx=3To8
IfRange("B"&x).Value Like"?[e-i]m"Then
Range("B"&x).Font.Color=vbRed
EndIf
Nextx
EndSub
|
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
|
SubCheckForNumber()
DimxAsInteger,yAsInteger
Forx=3To8
Fory=2To5
IfActiveSheet.Cells(x,y)Like"##"Then
ActiveSheet.Cells(x,y).Font.Color=vbRed
EndIf
Nexty
Nextx
EndSub
|
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
|
SubCheckFor9()
DimxAsInteger,yAsInteger
Forx=3To8
Fory=2To5
IfActiveSheet.Cells(x,y)Like"#9"Then
ActiveSheet.Cells(x,y).Font.Color=vbRed
EndIf
Nexty
Nextx
EndSub
|
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下