【发布时间】:2019-12-04 21:29:15
【问题描述】:
我正在尝试从具有多个工作表的 Excel 工作簿中删除过滤的行。我使用了动态范围,因为每张工作表的行数不同。
我尝试使用If 语句使代码循环通过一些特定的工作表,但它不起作用。没有ws.Activate,代码不会移动到其他工作表。
Sub DeletAnalyst2()
'Declare variables
Dim ws As Worksheet, startcell As Range, lastrow As Long, lastcol As Long
'Set Objects
Condition = Application.InputBox(prompt:="Please type the condition text:")
For Each ws In ThisWorkbook.Worksheets
ws.Activate
If (ws.Name <> "Presentation") And (ws.Name <> "Sheet6") And (ws.Name <> "sheet11") And (ws.Name <> "PrefTracks") And (ws.Name <> "AnalystNeeds") And (ws.Name <> "Post-Preference") And (ws.Name <> "Post Preference Grid") Then
Set startcell = Range("A1")
'Find last row and column of cells
lastrow = Cells(ws.Rows.Count, startcell.Column).End(xlUp).Row
lastcol = Cells(startcell.Row, ws.Columns.Count).End(xlToLeft).Column
'select dynamic range
Range(startcell, Cells(lastrow, lastcol)).Select
'AutoFilter technique
'ws.Range(startcell, ws.Cells(lastrow, lastcol))
Range(startcell, Cells(lastrow, lastcol)).AutoFilter Field:=1, Criteria1:=Condition
'deleting filtered
Selection.Offset(2).SpecialCells(xlCellTypeVisible).Delete Shift:=xlUp
ActiveSheet.ShowAllData
End If
Next
End Sub
我希望代码循环遍历一些工作表,但不是所有工作表。
【问题讨论】:
-
doesn't move to other sheets without ws.Activate.- 因为您需要 qualify 每个Range和Cells与ws通话。 -
例如:使用
Set startcell = ws.Range("A1")而不是Set startcell = Range("A1")。 Reading this 也可能有用。 -
当我设置 startcell = ws.range(A1) 时,代码会在 Range(startcell, Cells(lastrow, lastcol)) 处引发错误。选择 Hey Gserg,您的意思是为每个定义所有范围工作表?
-
if 语句不适用于此代码。代码正在遍历所有工作表,这不是我想要的。
-
@Meera 你对我的Answer 有同样的问题吗?