【Excel 支持正则的方法】解决VBA引入正则的方法和步骤

VBA本身不支持直接使用正则,需要引用Microsoft VBScript Regular Expressions库

方法 1:前期绑定(手动引用库)

  1. 打开 VBA 编辑器(按 Alt+F11)。
  2. 点击菜单栏的 工具 → 引用。
  3. 在弹出的窗口中勾选 Microsoft VBScript Regular Expressions 5.5,点击确定。

之后即可在代码中使用正则表达式:

vbnet 复制代码
Sub RegexExample()
    Dim regex As New RegExp
    Dim str As String
    Dim matches As MatchCollection
    
    str = "Hello 123 World 456"
    
    With regex
        .Global = True    ' 全局匹配
        .Pattern = "\d+"  ' 匹配数字
    End With
    
    If regex.Test(str) Then
        Set matches = regex.Execute(str)
        For Each match In matches
            MsgBox "找到匹配: " & match.Value
        Next
    End If
End Sub

方法 2:后期绑定(无需引用库)

如果你不想手动引用库,可以用 CreateObject 动态创建对象:

vbnet 复制代码
Sub RegexExample()
    Dim regex As Object
    Dim str As String
    Dim matches As Object
    
    Set regex = CreateObject("VBScript.RegExp")
    str = "Hello 123 World 456"
    
    With regex
        .Global = True
        .Pattern = "\d+"
    End With
    
    If regex.Test(str) Then
        Set matches = regex.Execute(str)
        For Each match In matches
            MsgBox "找到匹配: " & match.Value
        Next
    End If
End Sub

关键属性说明

  1. .Global:是否全局匹配(True 匹配所有,False 仅匹配第一个)。
  2. .Pattern:设置正则表达式规则(如 \d 匹配数字)。
  3. .IgnoreCase:是否忽略大小写(True 或 False)。
  4. .Execute():执行匹配,返回匹配结果的集合。
相关推荐
XDHCOM6 分钟前
ORA-12445报错:无法更改列隐藏属性,Oracle故障修复与远程处理,网友推荐解决方案
数据库·oracle
麒麟ZHAO11 分钟前
鸿蒙flutter第三方库适配 - 文件对比工具
数据库·redis·flutter·华为·harmonyos
香蕉鼠片13 分钟前
Redis
数据库·redis·缓存
翻斗包菜15 分钟前
第 03 章 Python 操作 MySQL 数据库实战全解
数据库·python·mysql
SPC的存折18 分钟前
1、MySQL故障排查与运维案例
linux·运维·服务器·数据库·mysql
小臭希21 分钟前
Redis(NoSQL数据库,Linux-Ubuntu环境下)
数据库·redis·缓存
cdcdhj22 分钟前
在window下将Mongodb单机改为副本集,只用于测试环境,实际上并没有增加真的副本集
数据库·mongodb
悟空码字24 分钟前
MySQL性能优化的天花板:10条你必须掌握的顶级SQL分析技巧
java·后端·mysql
xcjbqd027 分钟前
如何修改Oracle服务器默认的日期格式_NLS_DATE_FORMAT全局配置
jvm·数据库·python
HealthScience28 分钟前
SpliceVarDB数据集说明
数据库·oracle