我似乎无法弄清楚为什么这个包含正则表达式的函数不断返回错误数据类型的错误?我正在尝试从 excel 文档中的文件路径字符串返回与已识别模式的匹配项。我正在寻找的模式示例是来自示例字符串“H:\H1801100 MLK Middle School Hartford\2-Archive! Issued Bid Packages\01 Package_2018-0905 Demolition and Abatement Bid Set_Drawings”中的“02 Package_2018-1011” - 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)
结束函数
您需要使用\d{2}
来匹配 2 位块,而不是\D{2}
. 此外,您试图将整个匹配集合分配给函数结果,而您应该提取第一个匹配值并将该值分配给函数结果:
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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句