【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():执行匹配,返回匹配结果的集合。
相关推荐
凌虚5 小时前
面向 MySQL 用户的 PostgreSQL 快速上手指南
数据库·后端·架构
五阿哥永琪5 小时前
MySQL中操作json的函数!
数据库·mysql·json
来者皆善5 小时前
了解Mysql优化吗?如何优化索引?
数据库·mysql
赤壁小虾8 小时前
【渲染流水线】[逐片元阶段]-[透明度测试]以UnityURP为例
java·前端·数据库
MC皮蛋侠客8 小时前
SQLAlchemy 系列(七):高级建模与高效写入——批量 DML、方言与扩展
数据库·python
奈斯先生Vector9 小时前
把 Midjourney 二次编辑做成生产系统:customId 能力令牌、Action Graph 与 WebUI 精修工作台
数据库·人工智能·架构·aigc·音视频·midjourney
Lethehong9 小时前
双擎并驱·全链路并行:KFS让TB级异构增量同步秒级到达
数据库
MC皮蛋侠客9 小时前
SQLAlchemy 系列(八):AsyncIO、并发与 Web 生命周期——让每个并发任务持有自己的 Session
数据库·python
一水10 小时前
Redis实战:一个AI工作流系统里的五个应用场景,从传参到限流的完整链路
数据库·redis·wpf
Ai拆代码的曹操10 小时前
MySQL GROUP BY 性能优化:执行计划分析 + 索引重构实战
mysql·性能优化·重构