VBA中使用正则的两种方式
第一种方式(需要引用VBScript RegularExpression 5.5类库)
1 Option Explicit 2 3 Sub RegularExpresstion()'方法块 4 5 Dim regex AS New RegExp '绑定定义对象 6 7 With regex 8 9 .Global=True '匹配多次 10 11 .IgnoreCase=False '区分大小写 12 13 .Pattern="([0-9]+)-([0-9]+)[a-zA-Z]+" '正则表达式 14 15 End With 16 17 Dim m As Match 'Match对象 18 19 Dim mc as MatchCollection 'Match集合 20 Dim i as Integer 21 With Thisworkbook.Worksheets("Sheet1") 22 For i=1 To .Range("A65536").End(xlUp).Row 23 Set mc =regex.Execute(.Range("A" & i) '执行 24 '提取组 和C#有所区别(第一组不是全部表达式而是第一个圆括号内的内容) 25 '索引位置用SubMatches()方法,而不是Group[] 26 For Each m In mc 27 .Range("B" & i).Value=m.SubMatches(0) 28 .Range("C" & i).Value=m.SubMatches(1) 29 Next 30 Next 31 End With 32 End Sub
第二种方式(无需直接引用类库,创建新实例)
1 Option Explicit 2 Sub RegularExpression() 3 Dim reg As Object 4 Dim mc As Object 'Matchcollection 5 Dim m As Object 'Match 6 Set reg = CreateObject("VbScript.regexp") '创建正则项目 7 With reg 8 .Global =True '匹配多次 9 .IgnoreCase = False '匹配大小写 10 .Pattern = "[0-9A-Z]+" 正则表达式 11 End With 12 Set mc=reg.Execute(Range("E7")) '执行语句 13 For Each m In mc '遍历 14 MsgBox m 15 Next 16 End Sub