具有子字符串的Excel VBA自动筛选 [英] Excel VBA auto filter with substring

查看:231
本文介绍了具有子字符串的Excel VBA自动筛选的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的excel中有多行,其中D列为:TDM-02捆绑重定位5 NE,TDM-02捆绑重定位23 NE,IP-02捆绑重定位7 NE等.请注意,NE的数量在大多数地方. 我想搜索一个子字符串以在Excel VBA中自动过滤:

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

但是,这不会产生任何结果.没有生成错误,但结果为空行.
我尝试了其他各种选择,例如"Hybrid ATM and IP-02 Bundle Rehoming **"等,但没有成功. 有什么方法可以自动过滤这些带有可变结尾的子字符串.

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.

推荐答案

Regex

正则表达式\d+(?=\s*NE)

D列上的值和E列上的数字的代码,因此您可以过滤E列:

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

请记住启用引用

结果

我误解了,所以这里是对 Regex101 和代码的评论:

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

结果

因此您可以仅过滤数字来过滤其他列.

So you can filter for the other columns just for numbers.

这篇关于具有子字符串的Excel VBA自动筛选的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆