使用VBA删除列中与其他工作表中的值不匹配的所有行

时间:2017-03-28 11:35:34

标签: excel vba

我正在学习VBA,并且在使用两个工作表尝试在工作簿中开发宏时遇到了麻烦。第一个工作表名为“Para”,第二个工作表名为“Report”。

当我在Para!C6中输入一个数字或文本时(例如76894),我希望VBA代码删除列Report!Y:Y中的所有行,除了与该值匹配的行Para!C6

我尝试了以下代码,但它无效:

Sub KeepOnlyAtSymbolRows()
    Dim ws As Worksheet
    Dim rng As Range
    Dim lastRow As Long
    Dim s As Integer

    s = Worksheets("Para").Range("C6")

    Set ws = ActiveWorkbook.Sheets("Report")

    lastRow = ws.Range("Y" & ws.Rows.Count).End(xlUp).Row

    Set rng = ws.Range("A1:AR" & lastRow)

    ' filter and delete all but header row
    With rng
        .AutoFilter Field:=1, Criteria1:="<>*s*"
        .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete
    End With

    ' turn off the filters
    ws.AutoFilterMode = False
End Sub

1 个答案:

答案 0 :(得分:0)

尝试以下代码。

如果您的rng来自列“A”到列“AR”,并且您想根据“Y”列进行过滤,则需要过滤Field:=25(而不是Field:=1 ,即A列。)

此外,要根据变量的值进行过滤,您需要将变量名称s置于"之外,例如Criteria1:="<>" & s

<强>代码

Option Explicit

Sub KeepOnlyAtSymbolRows()

Dim ws          As Worksheet
Dim rng         As Range
Dim lastRow     As Long
Dim s           As Variant

s = Worksheets("Para").Range("C6").value

Set ws = ActiveWorkbook.Sheets("Report")    
With ws
    lastRow = .Range("Y" & .Rows.Count).End(xlUp).Row
    Set rng = .Range("A1:AR" & lastRow)
End With

' filter and delete all but header row
With rng
    .AutoFilter Field:=25, Criteria1:="<>" & s, Operator:=xlAnd
    .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete
End With

' turn off the filters
ws.AutoFilterMode = False

End Sub