【问题标题】:Excel VBA Macro - Loop Through Sheets & Clear RowsExcel VBA 宏 - 循环工作表和清除行
【发布时间】:2021-07-16 15:58:58
【问题描述】:

我试图让这个宏循环遍历工作簿中的所有工作表,然后过滤和清除一些单元格。当我没有启用宏的过滤/清除单元格部分时,循环工作但是只要我取消注释宏的过滤和清除部分,宏只会过滤和清除活动工作表中的单元格,有什么想法我哪里出错了吗?

非常感谢任何帮助!

Sub MovethroughWB()
    Dim ws As Worksheet
    For Each ws In Sheets 'This statement starts the loop
        If ws.Name <> "Exclusions" Then 'Exclude this sheet from the loop
            Range("D2:J2").Select
            Selection.AutoFilter
            ActiveSheet.Range("$D$2:$J$200").AutoFilter Field:=7, Criteria1:="<>#N/A", _
                Operator:=xlAnd
            Range("D3:J200").Select
            Selection.SpecialCells(xlCellTypeVisible).Select
            Selection.ClearContents
        End If
    Next ws
End Sub

【问题讨论】:

  • 您正在使用ws 作为循环的工作表变量,但它不用于限定您的Ranges(因此它假定ActiveSheet),然后您明确使用出于某种原因,ActiveSheet 而不是 ws
  • 阅读How to avoid using Select in Excel VBA可能会让您受益。
  • 我尝试输入 "ws.Range("D2:J2").Select" 但我只是得到 "Select method of Range class failed"
  • @Jonathan 不要使用.Select,请参阅我发布的链接。直接使用ws.Range("D2:J2").AutoFilter 之类的范围。使用.Select 是一种非常糟糕的做法,并且会带来很多不必要的副作用。

标签: excel vba loops


【解决方案1】:
  1. 为位于工作表中的每个对象(RangeCellsColumnsRows 等)引用工作表

  2. 停止使用.Select (How to avoid using Select in Excel VBA)。

您的代码变得可靠:

Sub MovethroughWB()
    Dim ws As Worksheet
    For Each ws In Sheets 'This statement starts the loop
        If ws.Name <> "Exclusions" Then 'Exclude this sheet from the loop
            ws.Range("D2:J2").AutoFilter
            ws.Range("$D$2:$J$200").AutoFilter Field:=7, Criteria1:="<>#N/A", Operator:=xlAnd
            ws.Range("D3:J200").SpecialCells(xlCellTypeVisible).ClearContents
        End If
    Next ws
End Sub

【讨论】:

    猜你喜欢
    • 2018-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多