我需要帮助才能使我的 Excel 函数正常工作。目标是运行一个单元内函数,该函数将正则表达式函数的所有模式匹配从另一个单元格的输入提取到一个单元格中,而不是单元格数组。
我已经尝试过使用一个数组,该数组在函数对话框预览中返回两个匹配项,但只输出单元格中的第一个匹配项。我也尝试过使用集合,但没有成功。
这是我当前的代码和将用作函数字符串输入的文本示例:
Function RegexMatches(strInput As String) As Variant
Dim rMatch As Match
Dim arrayMatches
Dim i As Long
arrayMatches = Array()
With New RegExp
.Global = True
.MultiLine = True
.IgnoreCase = True
.Pattern = "(Code)[\s][\d]{2,4}"
For Each rMatch In .Execute(strInput)
ReDim Preserve arrayMatches(i)
arrayMatches(i) = rMatch.Value
i = i + 1
Next
End With
RegexMatches = arrayMatches
End Function
来自 Excel 单元格的示例 strInput:
代码 123 一些随机文本
到这里继续下一行
代码 4567 后跟更多文字
包括换行而不仅仅是包装文本
此函数的所需输出是来自正则表达式函数的 (2) 个匹配值到单个单元格(例如“Code 123 Code 4567”)。
非常感谢任何帮助!
最佳答案
看起来您错过了函数的结尾(根据 Mat's Mug 的评论)?试试这个(根据 Wiktor 的评论)。
编辑:根据 Mat's Mug 的建议进行了修改。
Function RegexMatches(strInput As String) As String
Dim rMatch As Object
Dim s As String
Dim arrayMatches()
Dim i As Long
With New RegExp
.Global = True
.MultiLine = True
.IgnoreCase = True
.Pattern = "(Code)[\s][\d]{2,4}"
If .test(strInput) Then
For Each rMatch In .Execute(strInput)
ReDim Preserve arrayMatches(i)
arrayMatches(i) = rMatch.Value
i = i + 1
's = s & " " & rMatch
Next
End If
End With
RegexMatches = Join(arrayMatches, " ")
End Function
关于regex - 将多个匹配项返回到单个单元格中的 Excel VBA Regex 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44979363/