【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():执行匹配,返回匹配结果的集合。
相关推荐
❀͜͡傀儡师10 分钟前
MySQL REST Service 认证鉴权体系与 MySQL 26.10.0 内置化演进
数据库·mysql·adb
wifi___14 分钟前
Redis分布式锁
数据库·redis·分布式
4SAPI29 分钟前
营销内容生成大模型 API 生产选型指南:4SAPI、硅基流动与 OpenRouter 的架构权衡
数据库·人工智能·架构·php
zyxqyy&∞31 分钟前
sqli-labs-union联合查询(Less1-Less4)
数据库·安全
数据库小学妹39 分钟前
MySQL binlog格式怎么选?ROW、STATEMENT、MIXED的区别与坑
数据库·mysql·binlog·主从复制·数据一致性
小冯不疯1 小时前
查询旺店通货品策略实战教程:从源系统拉取到轻易云的端到端落地
java·大数据·数据库
花间相见1 小时前
【计算基础|MySQL18】Buffer Pool 与内存管理
后端·sql·mysql
RacentCLM1 小时前
HTTPS只在登录时有用?关于TLS的误解讲清
数据库·网络协议·https
杨云龙UP2 小时前
生产实战:Keepalived + Nginx + MySQL 双向复制高可用架构部署与原理详解
运维·数据库·mysql·nginx·架构·keepalived·高可用架构
代钦塔拉2 小时前
【C++/Qt 进阶】设计模式系列(7):过滤器模式——把“筛选条件“变成可组合的积木
数据库·系统架构