在excel VBA中,我试图在50张纸上运行一个简单的自动筛选器,但是,它只能在一张纸上运行。有人可以帮忙吗?代码如下:
Sub Macro2()
'
' Macro2 Macro
'
Dim wb As Workbook
For Each wb In Application.Workbooks
Range(Selection, Selection.End(xlToRight)).Select
Selection.AutoFilter
Selection.End(xlToLeft).Select
Range("G1").Select
ActiveSheet.Range("$A$1:$AC$91").AutoFilter Field:=7, Criteria1:=Array("11" _
, "21", "22", "23", "31-33", "42", "44-45", "48-49", "51", "52", "53", "54", "55", "56", "61" _
, "62", "71", "72", "81"), Operator:=xlFilterValues
Selection.End(xlToLeft).Select
Next wb
End Sub
答案 0 :(得分:3)
您的代码已经结束,但是...您正在遍历workbook
中的每个application
。相反,您要遍历worksheet
中的每个workbook
。此外,您在这里拥有所有这些随机.Select
代码。不用了您只需要在每个工作表中自动过滤一个范围:
Sub Macro2()
'
' Macro2 Macro
'
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
ws.Range("A1:AC91").AutoFilter Field:=7, Criteria1:=Array("11" _
, "21", "22", "23", "31-33", "42", "44-45", "48-49", "51", "52", "53", "54", "55", "56", "61" _
, "62", "71", "72", "81"), Operator:=xlFilterValues
Next ws
End Sub
每行都清晰明了,现在很简单。 1)循环浏览当前工作簿(thisworkbook
)中的每个工作表。 2)将自动过滤器应用于A1:AC91
。
答案 1 :(得分:1)
现在,您有一个For Each
循环,可循环访问所有打开的工作簿。我不确定这是否是您真正想要的,还是尝试将您的逻辑应用于单个工作簿的所有工作表,但是无论如何,Workbook
都有一个名为Worksheets
的集合您可以用相同的方式进行迭代。然后,在该循环内,您只需引用工作表循环变量即可,而不是ActiveSheet
。例如:
' Here's your existing loop, which I don't know if you really want to keep or not.
For Each wb In Application.Workbooks
' Here's a loop that will access every sheet within the 'wb' workbook.
For Each ws In wb.Worksheets
' Do your stuff here.
ws.Cells(2, 2).Value = "Hello!"
Next ws
Next wb