Translate

2013年6月19日 星期三

[VBA] Replace string by regular expression

https://github.com/walter426/VbaUtilities/blob/master/StrUtilities.bas

Although there are regular expression objects in VBA, it is too complicated when use it from zero.
There I have written below function to replace string by regular expression in an easy way.

Code:

'Replace substring by regular expression
'Ref: Microsoft VBScript Regular Expressions 5.5
Public Function Replace_RE(str As String, Pattern_f As String, substr_r As String) As String
    On Error GoTo Exit_Replace_RE
    
    Replace_RE = str
    
    Dim RE As RegExp
    Set RE = CreateObject("vbscript.regexp")
    
    With RE
        .MultiLine = True
        .Global = True
        .IgnoreCase = False
        .Pattern = Pattern_f
        
        Replace_RE = .Replace(str, substr_r)
    End With
    
Exit_Replace_RE:
    Exit Function

Err_Replace_RE:
    Call ShowMsgBox(Err.Description)
    Resume Exit_Replace_RE
End Function

沒有留言:

張貼留言