Excel VBA正则表达式函数将多个匹配返回到单个单元格

时间:2017-07-07 20:46:28

标签: regex vba excel-vba excel

我需要帮助让我的Excel功能正常工作。目标是运行一个in-cell函数,它将正则表达式函数的所有模式匹配从另一个单元格的输入提取到一个单元格中,而不是一个单元格数组。

我尝试使用一个数组,它在函数对话框预览中返回两个匹配项,但只输出单元格中的第一个匹配项。我也试过使用一个系列,但没有运气。

这是我当前的代码以及将用作函数字符串输入的文本示例:

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")。

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:2)

看起来你错过了你的功能结束(根据Mat的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