【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():执行匹配,返回匹配结果的集合。
相关推荐
catoop2 分钟前
Excel 实战技巧:单元格相对引用 INDIRECT、ROW、COLUMN 函数
excel
CoovallyAIHub14 分钟前
BMW GenAI4Q:每57秒下线一辆车,AI如何为每辆车定制专属质检清单
数据库·算法·架构
wang24559819922 分钟前
Redis基础——1、Linux下安装Redis(超详细)
linux·数据库·redis
oscar99923 分钟前
Memurai:Redis官方认可的Windows原生解决方案
数据库·windows·redis
A101693307124 分钟前
redis的启动方式
数据库·redis·bootstrap
IvorySQL27 分钟前
速看!HOW 2026 12 大分论坛出品人集结
数据库·postgresql·开源
V1ncent Chen33 分钟前
SQL大师之路 11 外连接和自连接
数据库·sql·mysql·数据分析
zklgin33 分钟前
PostgreSQL常用时间函数与时间计算提取示例说明
数据库·postgresql
曾阿伦35 分钟前
SQL CRUD 用法详解:从入门到实战的完整指南
数据库·sql
gaozhiyong081335 分钟前
SpringBoot连接多数据源MySQL、SqlServer等(MyBatisPlus测试)
spring boot·mysql·sqlserver