VBA like和通配符

返回 VBA 代码示例

VBA 通配符

本教程将演示如何在 VBA 中使用通配符。

通配符用于所有编程语言和数据库应用程序,如 SQL Server。通配符可以定义为用于替换文本字符串中的一个或多个字符的符号。例如,这个文本字符串 - “mo*” - 将找到单词 mom、mouse、moose、mommy 等;而这个文本字符串“mo?” 只会找到单词 mom 作为通配符?只替换一个字符。

我们将通配符与Like 运算符一起使用,它是VBA Regex的更简单替代方案

在 VBA 中使用 Asterix (*) 通配符

Asterix 通配符替换VBA 字符串中的一个或多个字符

让我们看一下Excel中的以下单元格区域:

VBA通配符范围

通过在我们的 VBA 代码中使用 Asterix 通配符,我们可以找到所有以“M”开头的名字并将文本的颜色更改为红色。

因此,我们遍历该范围并找到所有以字母 M 开头的名字,因为我们的通配符字符串是“ M*

运行上述代码的结果如下所示。

VBA通配符范围红色

 

如果我们使用通配符字符串“Ma*”——那么只有 B3 和 B4 中的名字会改变。

在 VBA 中使用问号 (?) 通配符

问号将替换 VBA 字符串中的单个字符。

考虑以下数据:

VBA通配符范围 QMark

 

我们可以使用通配符字符串“?im”来查找任何以“im”结尾的名字

运行此代码的结果如下所示:

VBAWildcard 范围 QMark 结果

 
 
 
 
 
 
 
 
 
 
AutoMacro - VBA 代码生成器

使用 [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.

The result of this code would be:

VBA通配符范围字符字符串

Using the hash (#) Wildcard in VBA

The hash (#) wildcard replaces a single digit in a VBA string.   We can match between 0 to 9.

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.

VBA通配符范围数

In the example below, the code will only change the number if the last number is a 9.

VBA通配符范围SpecificNumber

 



posted @   uuxyz  阅读(2903)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下
联系我
点击右上角即可分享
微信分享提示