I'm trying to pass a Regex pattern to a Function in Excel VBA, but the pattern seems to be of none effect. I've inserted msgbox'es to see what the string looks like, and they turn out ok. Here's the code I'm using.
Sub clean_COP_names()
Dim strSheet As String
Dim strPatternOrig As String
Dim strRow As Integer
Dim strCol As Integer
Dim UpBound As Range
Dim LowBound As Range
Dim strUpBoundRow As Integer
Dim strUpBoundColumn As Integer
Dim strLowBoundRow As Integer
Dim strLowBoundColumn As Integer
Dim CompareRange As Range
Dim c As Variant
Dim d As Integer
Dim strTest As String
strTest = ActiveCell.Value
strSheet = "Sheet2"
strRow = 2
strCol = 2
strUpBoundRow = 0
strUpBoundColumn = 0
strLowBoundRow = 0
strLowBoundColumn = 0
'/////call ext function
SelectColumn strSheet, strRow, strCol, strUpBoundRow, strUpBoundColumn, strLowBoundRow, strLowBoundColumn
Set CompareRange = Worksheets(strSheet).Range _
(Cells(strUpBoundRow, strUpBoundColumn), Cells(strLowBoundRow, strLowBoundColumn))
d = 1
Cells(d, 6).Value = "Alumni Officer - Last,First names"
strPatternOrig = """^([^ ]+)([ ]+)([^ ]+)([ ]+)([^ ]+)(.*)$"""
'MsgBox (strPatternOrig)
For Each c In CompareRange
d = d + 1
'/////ext function
Cells(d, 6).Value = Reorder_Name_COP_Data_a(c.Value, strPatternOrig, "$3,$1")
Next
End Sub
Function Reorder_Name_COP_Data_a(strData As String, strPattern As String, strReplacementPattern As String) As String
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
With RE
.MultiLine = False
'.Global = False
.Global = True
.IgnoreCase = True
'MsgBox (strPattern)
.Pattern = strPattern
End With
Reorder_Name_COP_Data_a = RE.Replace(strData, strReplacementPattern)
End Function
==================
addendum apr 26,2012 Many thanks-
I've noticed that the problem persists when I use escaped quotes as below:
strPatternOrig = "^[ ]?([^\ ,()""'']+)(?:[ ](\(([^)]*?)\)))?[ ]((?:(([^\ ,()""''])[^\ ,()""'']*)[ ])([^\ ,()""'']+(?:[ ][^\ ,()""'']+)*))(?: [ ]? , [ ]?(.*?))?[ ]?(\(\s*'*\d*\s*\))[ ]?$"
Do the double and single quotes need to be escaped in a different way, possibly? The above worked when the Regex pattern was 'hard wired' into the function, but when it's passed to the function, it fails. Thanks again.