excel - VBA 代码中的 IF 语句对于每个 next 都失败
问题描述
我正在尝试从具有多个工作表的 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
我希望代码循环遍历一些工作表,但不是所有工作表。
解决方案
您需要对所有调用以及它们所属的工作表进行限定,否则您将无意中引用活动工作表中的单元格。Range
Cells
你也不需要任何Select
东西。
Sub DeletAnalyst2()
'Declare variables
Dim ws As Worksheet, startcell As Range, lastrow As Long, lastcol As Long
Dim Condition As String
'Set Objects
Condition = Application.InputBox(prompt:="Please type the condition text:")
For Each ws In ThisWorkbook.Worksheets
Select Case ws.Name
Case "Presentation", "Sheet6", "sheet11", "PrefTracks", "AnalystNeeds", "Post-Preference", "Post Preference Grid"
'Do nothing
Case Else
With ws
Set startcell = .Range("A1")
'Find last row and column of cells
lastrow = .Cells(.Rows.Count, startcell.Column).End(xlUp).Row
lastcol = .Cells(startcell.Row, ws.Columns.Count).End(xlToLeft).Column
'select dynamic range
With .Range(startcell, .Cells(lastrow, lastcol))
.AutoFilter Field:=1, Criteria1:=Condition
.Offset(2).SpecialCells(xlCellTypeVisible).Delete Shift:=xlUp
End With
.ShowAllData
End With
End Select
Next
End Sub
推荐阅读
- java - 日期格式的 Java 常量名称约定
- java - 在 MSSQL (Java) 中为“图像”类型生成 INSERT
- javascript - 如何使用 YouTube API 从特定时间获取帧作为图片
- stata - 如何使用Stata计算随时间变化的历史平均值
- javascript - 如何在每次执行另一个函数之前检查一个函数是否已被调用
- ios - 如何在依赖注入模式中修改对象
- javascript - 使用 javascript 记录用户会话,以便稍后使用谷歌分析(离线)进行分析
- stm32 - STM32热初始化一个1 us-timer?
- c# - 帖子忽略格式后格式化文本框
- c# - 具有 C# 结构的生产者/消费者?