一、關於起因
最近在Office的QQ群里問如何在一串字符串中提取數值並加總的問題。如果使用正則表達式可以非常迅速的解決這個問題。
那么今天我就探討一下在VB6/VBA中使用正則表達式的方法及代碼,另外為了快速測試正則表達式,我給大家推薦notepad++及使用方式。
二、操作步驟
1、按Alt+F11進入Excel的VBE環境,依次選擇“工具/引用”菜單,選擇“Microsoft VBScript Regular Express”;
2、插入一個模塊,在模塊中輸入如下所示的代碼;
1 Function SumValueInText(TargetRange As Range) As Double 2 Dim mRegExp As RegExp 3 Dim mMatches As MatchCollection '匹配字符串集合對象 4 Dim mMatch As Match '匹配字符串 5 6 Set mRegExp = New RegExp 7 With mRegExp 8 .Global = True 'True表示匹配所有, False表示僅匹配第一個符合項 9 .IgnoreCase = True 'True表示不區分大小寫, False表示區分大小寫 10 .Pattern = "([0-9])?[.]([0-9])+|([0-9])+" '匹配字符模式 11 Set mMatches = .Execute(TargetRange.Text) '執行正則查找,返回所有匹配結果的集合,若未找到,則為空 12 For Each mMatch In mMatches 13 SumValueInText = SumValueInText + CDbl(mMatch.Value) 14 Next 15 End With 16 17 Set mRegExp = Nothing 18 Set mMatches = Nothing 19 End Function
3、在工作表的A列單元格中輸入各種測試字符串,在B列單元格中輸入自定義函數進行測試,結果如下圖所示;
三、Attention
在VB6/VBA中使用正則表達式時,我們也可以省去第一步,即采用后期綁定的方式來使用正則表達式,但是代碼要做相應的調整,如下所示為調整后的代碼。
1 Function SumValueInText(TargetRange As Range) As Double 2 Dim mRegExp As Object '正則表達式對象 3 Dim mMatches As Object '匹配字符串集合對象 4 Dim mMatch As Object '匹配字符串 5 6 Set mRegExp = CreateObject("Vbscript.Regexp") 7 With mRegExp 8 .Global = True 'True表示匹配所有, False表示僅匹配第一個符合項 9 .IgnoreCase = True 'True表示不區分大小寫, False表示區分大小寫 10 .Pattern = "([0-9])?[.]([0-9])+|([0-9])+" '匹配字符模式 11 Set mMatches = .Execute(TargetRange.Text) '執行正則查找,返回所有匹配結果的集合,若未找到,則為空 12 For Each mMatch In mMatches 13 SumValueInText = SumValueInText + CDbl(mMatch.Value) 14 Next 15 End With 16 17 Set mRegExp = Nothing 18 Set mMatches = Nothing 19 End Function