问题
There are multiple rows in my excel with D column as: TDM - 02 Bundle Rehoming 5 NE, TDM - 02 Bundle Rehoming 23 NE, IP - 02 Bundle Rehoming 7 NE etc. Please note that the number of NEs are different at most of the places. I want to search a substring to auto filter in Excel VBA:
sht2.Select
sht2.Activate
If sht2.FilterMode Then
sht2.ShowAllData
End If
sht2.Range("D1:D" & LastRow).AutoFilter Field:=4, Criteria1:=Array( _
CStr("HYBRID ATM and IP - 02 Bundle Rehoming" & Chr(42)), _
CStr("TDM - 02 Bundle Rehoming" & Chr(42)), _
CStr("IP - 02 Bundle Rehoming" & Chr(42))), Operator:=xlFilterValues
However, This won't produce any results. There is no error generated but the results are empty rows.
I tried various other options such as "HYBRID ATM and IP - 02 Bundle Rehoming **" etc but without any success.
Is there any way to auto-filter these substrings with having a variable ending.
回答1:
Regex
The Regex101 for the regex \d+(?=\s*NE)
The code for values on column D and writting the number on column E, so you can filter for column E:
Dim str As String
Dim objMatches As Object
lastrow = Cells(Rows.Count, "D").End(xlUp).Row
For i = 1 To lastrow
str = Cells(i, "D")
Set objRegExp = CreateObject("VBScript.RegExp") 'New regexp
objRegExp.Pattern = "\d+(?=\s*NE)"
objRegExp.Global = True
Set objMatches = objRegExp.Execute(str)
If objMatches.Count > 0 Then
For Each m In objMatches
Cells(i, "E") = m.Value
Next
End If
Next i
Remember to enable the reference
Result
Edit:
I misunderstood it, so here is a review of the Regex101 and code:
Dim str As String
Dim objMatches As Object
lastrow = Cells(Rows.Count, "D").End(xlUp).Row
For i = 1 To lastrow
str = Cells(i, "D")
Set objRegExp = CreateObject("VBScript.RegExp") 'New regexp
objRegExp.Pattern = "\d+(?=\s*NE)"
objRegExp.Global = True
Set objMatches = objRegExp.Execute(str)
If objMatches.Count > 0 Then
k = 5
For Each m In objMatches
Cells(i, k) = m.Value
k = k + 1
Next
End If
Next i
Result
So you can filter for the other columns just for numbers.
回答2:
You can provide a "regex" or an array of explicit values, but not an array of "regex". What you could do is create a loop that finds all the values you're looking for and provide those as an array.
来源:https://stackoverflow.com/questions/46960980/excel-vba-auto-filter-with-substring