文章目录[隐藏]
本篇介绍如何在Excel 的VBA 巨集程式中,使用正规表示法(regular expression)匹配与取代文字。
正规表示法
正规表示法(regular expression,也称为常规表示法、正规表示式等)是专门用来匹配、取代文字资料的语法规则,在处理各种复杂的文字处理问题时,正规表示法是不可或缺的工具之一。
多数的程式语言与软体都有支援正规表示法,语法大同小异,在Excel 与VBA 巨集程式之中亦可使用。
匹配文字
若要在VBA 巨集程式中,使用正规表示法匹配文字,可以先建立一个正规表示法的 RegExp
Pattern
Text
在这个范例的匹配规则中,w+
aw+e
a
e
apple
如果在执行含有正规表示法的VBA 巨集程式时,出现了「使用者自订型态尚未定义」的编译错误,请
取代文字
若要将匹配的文字以新的文字取代,可以使用 RegExp
Replace
Test
取代所有符合文字
RegExp
的 Replace
Dim Dim regEx Dim
执行后的结果为:

如果想讓程式一次把原始文字中,所有符合的文字一次全部取代掉,可以將 RegExp
物件的 Global
全域選項設定為 True
,這樣就可以取代所有符合的部分:
Dim regEx As New RegExp Dim MyText As String MyText = "吃葡萄不吐葡萄皮,不吃葡萄倒吐葡萄皮。" regEx.Pattern = "葡萄" Dim MyReplace As String MyReplace = "香蕉" regEx.Global = True If regEx.Test(MyText) Then Result = regEx.Replace(MyText, MyReplace) MsgBox ("取代後的文字:" & Result) Else MsgBox ("匹配失敗") End If
將所有符合的部分取代之後,結果就會像這樣:

不分大小寫
RegExp
預設在匹配英文字母時,會區分大寫與小寫,也就是說會將大寫與小寫視為不同的文字,若想要讓 RegExp
在匹配文字時,不區分大小寫的話,可以將 IgnoreCase
設定為 True
:
Dim regEx As New RegExp Dim MyText As String MyText = "Apple APPLE aPPLe APpLe" regEx.Pattern = "apple" Dim MyReplace As String MyReplace = "orange" regEx.Global = True regEx.IgnoreCase = True If regEx.Test(MyText) Then Result = regEx.Replace(MyText, MyReplace) MsgBox ("取代後的文字:" & Result) Else MsgBox ("匹配失敗") End If
執行結果為:

多行文字
正規表示法的 ^
與 $
可以匹配整個字串的開頭與結尾,如果我們的原始文字資料包含很多行的時候,這兩個字符只會匹配整段的文字的開頭與結尾(也就是不管中間的換行字元的意思)。
以下這個範例我們想要把每一行開頭的 This
替換成 THAT
,但如果按照預設的方式,只會替換掉第一行的 This
,第二行以後的 This
會被忽略:
Dim regEx As New RegExp Dim MyText As String MyText = "This is the first line." & vbNewLine & _ "This is the second line." & vbNewLine & _ "This is the third line." regEx.Pattern = "^This" Dim MyReplace As String MyReplace = "THAT" regEx.Global = True If regEx.Test(MyText) Then Result = regEx.Replace(MyText, MyReplace) MsgBox ("取代後的文字:" & Result) Else MsgBox ("匹配失敗") End If

遇到這樣的狀況時,可以將 MultiLine
屬性設定為 True
,以多行模式進行匹配,這樣 ^
與 $
就會匹配每一行文字的開頭與結尾:
Dim regEx As New RegExp Dim MyText As String MyText = "This is the first line." & vbNewLine & _ "This is the second line." & vbNewLine & _ "This is the third line." regEx.Pattern = "^This" Dim MyReplace As String MyReplace = "THAT" regEx.Global = True regEx.MultiLine = True If
执行的结果如下:
