我的excel中有多行,其中D列为:TDM-02 Bundle Rehoming 5 NE,TDM-02 Bundle Rehoming 23 NE,IP-02 Bundle Rehoming 7 NE等。请注意,在大多数情况下,NE的数量不同的地方。我想搜索一个子字符串以在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
但是,这不会产生任何结果。没有生成错误,但是结果为空行。
我尝试了其他各种选择,例如“ Hybrid ATM and IP-02 Bundle Rehoming **”等,但没有成功。有什么方法可以自动过滤这些带有可变结尾的子字符串。
regex的Regex101\d+(?=\s*NE)
D列上的值和E列上的数字的代码,因此您可以筛选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
记住要启用参考
我误解了,所以这里是Regex101和代码的回顾:
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
因此,您可以仅针对数字过滤其他列。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句