[英]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.