【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():执行匹配,返回匹配结果的集合。
相关推荐
城北徐宫1 小时前
MySQL基础与库、表操作
数据库·mysql
码完就睡2 小时前
Redis——初识 Redis
数据库·redis·缓存
飞花漫卷,情随岁迁6 小时前
网络数据包转发与内核机制:小白概念科普
linux·运维·网络·数据库·mysql·oracle·智能路由器
FungLeo6 小时前
FengCMS·PHP+MySQL 升级实录 ·本地容器环境设计:只读挂载、LOCAL_UID、数据卷权限
开发语言·mysql·docker·php·fengcms
wangxiaoxuan2177 小时前
大模型怎样调用机器人能力:目标落地、工具调用与执行反馈
数据库·机器人·php
数据世界110 小时前
从立项选品到竞争情报:医药人查询国内品种格局数据的难点与5.0版结构化整理
大数据·数据库·人工智能
千寻技术帮11 小时前
基于微信小程序的校园美食评鉴系统(附完整源码+数据库+部署文档)50049
mysql·微信小程序·小程序·毕业设计·美食
用户2986985301411 小时前
在 React 中实现 Excel 文本与数字互转的完整实践
javascript·react.js·excel