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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM