提出一个可能非常简单的答案的问题,但我仍然在使用VBA进行便盆训练。我循环遍历一个excel数组并在一个很长的字符串中搜索正则表达式模式"\.\w*?_\w*?_Tag_\w*?"
。在this post下,在接受的答案" 示例3 :循环范围内,有一个类似的例子。"
不是查找和替换文本,而是希望在单个消息框中显示数组中每个单元格的匹配搜索模式。我已经搜索了几个小时,但我发现大多数VBA Regex示例都使用了内置函数(不会循环通过数组),但由于这将被其他人使用我需要使用宏。
这是我到目前为止所拥有的。我认为我需要在For Each循环之外的另一个循环,但不知道如何开始执行此循环。
Sub TagNameList()
Dim strPattern As String: strPattern = "\.\w*?_\w*?_Tag_\w*?"
Dim Regx As New RegExp
Dim StrInput As String
Dim Rng As range
Dim LastRow As Long: LastRow = ActiveSheet.UsedRange.Rows.Count
' Set Rng = ActiveSheet.range(Cells(2, 16), Cells(LastRow, 16))
' Set RegxMatch = Regx.Execute(StrInput)
For Each cell In Rng
StrInput = cell.Value
With Regx
.Global = True
.MultiLine = True
.IgnoreCase = True
.Pattern = strPattern
End With
' If Regx.Test(StrInput) Then
' MsgBox (Regx.Replace(StrInput, strReplace))
' Else
' MsgBox ("Not matched")
' End If
Next
End Sub
答案 0 :(得分:0)
我不清楚你是指整个范围的消息框还是每个单元格的消息框,但是你需要使用匹配集合,例如。
Sub TagNameList()
Dim strPattern As String: strPattern = "\.\w*?_\w*?_Tag_\w*?"
Dim Regx As New RegExp
Dim StrInput As String
Dim Rng As Range
Dim LastRow As Long: LastRow = ActiveSheet.UsedRange.Rows.Count
Dim oMatches As Object, s As String
Set Rng = ActiveSheet.Range(Cells(2, 16), Cells(LastRow, 16))
Set RegxMatch = Regx.Execute(StrInput)
For Each cell In Rng
StrInput = cell.Value
With Regx
.Global = True
.MultiLine = True
.IgnoreCase = True
.Pattern = strPattern
If .Test(cell) Then
Set oMatches = .Execute(cell)
s = s & "," & oMatches(0).Value
End If
End With
Next
MsgBox Mid(s, 2)
End Sub