如何在VBA中排除某些行

时间:2019-02-25 09:05:55

标签: excel vba

我正在寻找此代码的替代方法。我需要选择所有名称为“ export 1”,“ export 2”等的行,但不包括“ export test”

Sub CopyManager()
    Dim Source As Worksheet
    Dim Target As Worksheet
    Dim valsArray As Variant


     valsArray = Array("Export *") '<--| define your values to be filtered on Source sheet column A
    ' Change worksheet designations as needed
    Set Source = ActiveWorkbook.Worksheets("Sheet1")
    Set Target = ActiveWorkbook.Worksheets("Export")

    With Source  '<--| reference Source sheet
        With .Range("A1:A1000")  '<--| reference its range from A1 to A1000
            .AutoFilter Field:=1, Criteria1:=valsArray, Operator:=xlFilterValues   '<--| filter referenced range on its first column with values stored in valsArray
            If Application.WorksheetFunction.Subtotal(103, .Cells) > 1 Then '<--| if any cell filtered other than
                .Resize(.Rows.Count - 1, 1).Offset(1, 0).SpecialCells(xlCellTypeVisible).Copy Target.Range("A2") '<--|copy filtered cells skipping headers and paste in target sheet from cell A1
                .Resize(.Rows.Count - 1, 1).Offset(1, 4).SpecialCells(xlCellTypeVisible).Copy Target.Range("B2")
            End If
        End With
        .AutoFilterMode = False
    End With

End Sub

上面的代码将复制名称为“ export 1”,“ export 2”等的所有行,并且还包括“ export test”,但我需要排除“ export test”

2 个答案:

答案 0 :(得分:0)

我不太确定,但是一种可能的解决方案是

替换

itms-podcasts://

具有:

.AutoFilter Field:=1, Criteria1:=valsArray, Operator:=xlFilterValues 

答案 1 :(得分:0)

您可以在自动过滤器中添加第二个条件。
将运算符更改为<>,并使用.AutoFilter Field:=1, Criteria1:=valsArray, Operator:=xlAnd, Criteria2:="<>Export test" 添加排除条件:

{{1}}

很明显,您可以将此条件作为变量,就像需要过滤条件一样。