简体   繁体   English

使用 VBA 自动过滤特定条件

[英]Autofilter Specific Criteria Using VBA

I am using trying to autofilter items using VBA.我正在尝试使用 VBA 自动过滤项目。

The issue is that each list item has slashes in-between them.问题是每个列表项之间都有斜线。 For example, (ABC/EFG/HIJ).例如,(ABC/EFG/HIJ)。 I want to pull out the list items that just contain the string "ABC," whether that is alone or listed along with other string items.我想取出只包含字符串“ABC”的列表项,无论是单独的还是与其他字符串项一起列出的。 For example, if one list item says (ABC/EFG) and another list items says (ABC), I want both of those items, because both of those items contain the ABC string by itself.例如,如果一个列表项显示 (ABC/EFG),另一个列表项显示 (ABC),我想要这两个项,因为这两个项本身都包含 ABC 字符串。 This is what I have so far:这是我到目前为止:

Sub FilterByABC()

'Change this to the relevant worksheet
Set ws = ThisWorkbook.Sheets("ABC")
Worksheets("ABC").Range("A1").AutoFilter , Field:=1, Criteria1:="ABC"
Operator = xlFilterValues
Range("A1").Select

Columns("A").Copy
Sheets("ABCData").Select
Columns("A").Select
Worksheets("ABCData").Paste


End Sub

Add a second wildcard filter and the Operator:=xlAnd parameter.添加第二个通配符过滤器和Operator:=xlAnd参数。

在此处输入图片说明

Option Explicit

Sub FilterByABC()
    Dim rngDest As Range

    With Worksheets("ABCData")
        Set rngDest = .Cells(.Rows.Count, "A").End(xlUp).Offset(1, 0)
    End With

    With Worksheets("ABC")
        If .AutoFilterMode Then .AutoFilterMode = False
        With .Cells(1, 1).CurrentRegion
            .AutoFilter Field:=1, Criteria1:="ABC*", _
                        Operator:=xlAnd, Criteria2:="<>ABC EC*"
            With .Resize(.Rows.Count - 1, 1).Offset(1, 0)
                If CBool(Application.Subtotal(103, .Cells)) Then
                    'there are visible, filtered cells in column A; copy then to ABCData
                    .SpecialCells(xlCellTypeVisible).Copy Destination:=rngDest
                End If
            End With
        End With
        If .AutoFilterMode Then .AutoFilterMode = False
    End With
End Sub

在此处输入图片说明

You should add two criteria to achieve that:您应该添加两个标准来实现这一目标:

Sub FilterByABC()

'Change this to the relevant worksheet
Set ws = ThisWorkbook.Sheets("ABC")
Worksheets("ABC").Range("A1").AutoFilter , Field:=1, _
                          Criteria1:="ABC*", Operator:= xlAnd, Criteria2:="<>ABD EC"
Operator = xlFilterValues
Range("A1").Select

Columns("A").Copy
Sheets("ABCData").Select
Columns("A").Select
Worksheets("ABCData").Paste


End Sub

Also read Why you should avoid using select?另请阅读为什么您应该避免使用选择? . .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM