【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():执行匹配,返回匹配结果的集合。
相关推荐
富贵儿9985 小时前
NL2SQL 实践手记 05:表结构之外,还有业务知识——给查询流程接上 RAG
数据库·sql·ai·自然语言处理·langchain
csdn_aspnet7 小时前
如何使用 Docker 设置 PostgreSQL
运维·数据库·docker·postgresql·容器
皮皮林5517 小时前
CTO说MySQL单表行数不要超过2000w,为啥?
mysql
倔强的石头_9 小时前
KES Studio 与 DMS 辅助开发管理实践:让接入过程可视化
数据库
富贵儿99810 小时前
NL2SQL 实践手记 06:四个角色怎样合作——拆解一个 Multi-Agent 查询系统
数据库·sql·ai·自然语言处理·langchain
codeejun11 小时前
每日一Go·MySQL-24、死锁排查与解决方案
开发语言·mysql·golang
Decay__13 小时前
PostgreSQL 监控体系构建 —— postgres_exporter + Prometheus + Grafana 全栈实战
运维·数据库·sql·postgresql
码农张314 小时前
MySQL 8.4.13 LTS 压缩版安装步骤 + 规范配置文件
mysql
Decay__14 小时前
PostgreSQL 告警与自动化运维 —— 告警分级收敛、Webhook、定时巡检、脚本库
运维·数据库·sql·postgresql
老纪的技术唠嗑局15 小时前
OceanBase × 知跃空间智能:从感知,到记忆,再到行为,打造具身智能数据底座
数据库