我正在学习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
答案 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