【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():执行匹配,返回匹配结果的集合。
相关推荐
o_oer1 小时前
mysql type
mysql
花卷持续成长1 小时前
慢SQL的整体优化思路
后端·mysql
用户8662978480081 小时前
KingbaseES 中文乱码、排序不对?区域和字符集的问题,一次说清
数据库
aruo1 小时前
回退旧镜像之前,先确认数据库还能兼容
数据库
张洛闻Eren1 小时前
Ansible【第三课】:管理变量和事实
数据库·oracle
鱼很腾apoc2 小时前
【MySQL】第3期 索引、事务与视图系统详解
linux·mysql·事务·索引·dml·视图·macc
泡海椒2 小时前
从 XML 到 Excel:JQuick-Excel 代理与解析器如何协作
xml·excel
weixin_382395232 小时前
0-500 人工厂的生产 PMC 系统怎么做?基于 Tauri + SQLite 的性能架构实践与 5000 物料压测实录
数据库·架构·sqlite
l1t3 小时前
DeepSeek总结的 DuckDB 2.0 文档新内容
服务器·网络·数据库
IvorySQL3 小时前
PostgreSQL 日报| PG19 主备切换挂起修复(10 月 17 日)
数据库·postgresql