简体   繁体   English

Excel VBA 宏 - 循环工作表和清除行

[英]Excel VBA Macro - Loop Through Sheets & Clear Rows

I am trying to get this macro to loop through all sheets within a workbook & then filter & clear some cells.. the loop works when I do not have the filter/clear cells part of the macro enabled however as soon as I uncomment the filter & clear part of the macro, the macro will only filter and clear the cells within the Active Sheet, any ideas where I am going wrong?我试图让这个宏循环遍历工作簿中的所有工作表,然后过滤并清除一些单元格..当我没有启用宏的过滤器/清除单元格部分时,循环工作但是一旦我取消注释过滤器& 清除宏的一部分,宏只会过滤和清除活动表中的单元格,我哪里出错了?

Any help very much appreciated!非常感谢任何帮助!

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
  1. Referce a worksheet for every object that is located in a worksheet ( Range , Cells , Columns , Rows , etc)为工作表中的每个对象( RangeCellsColumnsRows等)引用工作表

  2. Stop using .Select ( How to avoid using Select in Excel VBA ).停止使用.Select如何避免在 Excel VBA 中使用 Select )。

And your code gets reliable:并且您的代码变得可靠:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM