【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():执行匹配,返回匹配结果的集合。
相关推荐
llilian_161 天前
IRIG-B码产生器立足用户痛点,提供精准授时解决方案
大数据·数据库·功能测试·单片机·嵌入式硬件·测试工具
zuoerjinshu1 天前
sql实战解析-sum()over(partition by xx order by xx)
数据库·sql
NocoBase1 天前
【2.0 教程】第 1 章:认识 NocoBase ,5 分钟跑起来
数据库·人工智能·开源·github·无代码
Hoshino.411 天前
基于Linux中的数据库操作——下载与安装(1)
linux·运维·数据库
Oueii1 天前
Django全栈开发入门:构建一个博客系统
jvm·数据库·python
未来龙皇小蓝1 天前
【MySQL-索引调优】11:Group by相关概念
数据库·mysql·性能优化
2401_831824961 天前
使用Fabric自动化你的部署流程
jvm·数据库·python
njidf1 天前
Python日志记录(Logging)最佳实践
jvm·数据库·python
twc8291 天前
大模型生成 QA Pairs 提升 RAG 应用测试效率的实践
服务器·数据库·人工智能·windows·rag·大模型测试
@我漫长的孤独流浪1 天前
Python编程核心知识点速览
开发语言·数据库·python