我似乎无法弄清楚为什么此包含正则表达式的函数会不断返回错误数据类型的错误?我正在尝试从Excel文档中的文件路径字符串返回与已识别模式的匹配项。我要寻找的模式的示例是示例字符串“ H:\ H1801100 MLK中学Hartford \ 2-Archive!的示例字符串中的” 02 Package_2018-1011”!已发布的投标Packages \ 01 Package_2018-0905拆除和减低的投标Set_Drawings-PDF \ 00 HazMat \ HM-1.pdf”。下面列出了VBA代码的副本。
Function textpart(Myrange As Range) As Variant
Dim strInput As String
Dim regex As Object
Set regex = CreateObject("VBScript.RegExp")
strInput = Myrange.Value
With regex
.Pattern = "\D{2}\sPackage_\d{4}-\d{4}"
.Global = True
End With
Set textpart = regex.Execute(strInput)
结束功能
答案 0 :(得分:0)
您需要使用\d{2}
来匹配2位数的块,而不是\D{2}
。此外,您尝试将整个match集合分配给函数结果,同时应提取第一个匹配值并将该值分配给函数结果:
Function textpart(Myrange As Range) As Variant
Dim strInput As String
Dim regex As Object
Dim matches As Object
Set regex = CreateObject("VBScript.RegExp")
strInput = Myrange.Value
With regex
.Pattern = "\d{2}\sPackage_\d{4}-\d{4}"
End With
Set matches = regex.Execute(strInput)
If matches.Count > 0 Then
textpart = matches(0).Value
End If
End Function
请注意,要使其整体匹配,可以添加单词边界:
.Pattern = "\b\d{2}\sPackage_\d{4}-\d{4}\b"
^^ ^^
要仅在\
之后匹配它,可以使用捕获组:
.Pattern = "\\(\d{2}\sPackage_\d{4}-\d{4})\b"
' ...
' and then
' ...
textpart = matches(0).Submatches(0)