[英]Excel VBA Regex Function That Returns Multiple Matches Into A Single Cell
我需要帮助以使我的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的杯子的评论)? 尝试一下(按照Wiktor的评论)。
编辑:根据Mat的杯子的建议进行了修改。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.