用Excel的VBA实现文本匹配与替换

在工作的过程中,有时候为了批量处理Excel,不可避免会写一些VBA小程序,而在规范数据格式方面,经常会用正则表达式:

以下是我自己经常会用到的小程序:

一、文本匹配

Function bTest(ByVal s As String, ByVal p As String) As Boolean
Dim re
    Set re = CreateObject("VBScript.RegExp")
     re.IgnoreCase = False '设置是否匹配大小写
re.Pattern = p
bTest = re.Test(s)
End Function

二、文本替换

Function StrReplace(s As String, p As String, r As String) As String

Dim re
    Set re = CreateObject("VBScript.RegExp")
    re.IgnoreCase = True
re.Global = True
re.Pattern = p
StrReplace = re.Replace(s, r)

End Function

当然,往往在实际的应用中,还要根据具体的情况去修改程序。

 

posted @ 2011-09-21 15:22  candy.huang  阅读(6801)  评论(0编辑  收藏  举报