我正在尝试将正则表达式模式传递给 Excel VBA 中的函数,但该模式似乎无效。我已插入 msgbox'es 以查看字符串的外观,结果正常。这是我正在使用的代码。
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
===================
附录 2012 年 4 月 26 日 非常感谢-
我注意到当我使用如下转义引号时问题仍然存在:
strPatternOrig = "^[ ]?([^\ ,()""'']+)(?:[ ](\(([^)]*?)\)))?[ ]((?:(([^\ ,()""''])[^\ ,()""'']*)[ ])([^\ ,()""'']+(?:[ ][^\ ,()""'']+)*))(?: [ ]? , [ ]?(.*?))?[ ]?(\(\s*'*\d*\s*\))[ ]?$"
双引号和单引号是否需要以不同的方式转义,可能吗?当正则表达式模式“硬连线”到函数中时,上述方法有效,但是当它传递给函数时,它失败了。再次感谢。