在运行实际宏之前,VBA可能会停用自动过滤器

时间:2017-08-31 06:32:48

标签: excel-vba vba excel

有没有办法在宏中包含一些允许停用自动过滤器的代码,然后运行实际的宏,然后重新激活自动过滤器?

  1. 自动过滤器停用代码

  2. 原始宏代码

  3. 自动过滤器重新激活代码

  4. 我问,因为我的原始宏不会对自动过滤器激活的数据起作用。

2 个答案:

答案 0 :(得分:1)

ActiveSheet.AutoFilterMode = False

将ActiveSheet更改为所需的工作表/变量名称

答案 1 :(得分:1)

要停用特定的过滤器 Worksheet

Workbook("WorkbookName").Worksheets("SheetName").AutoFilterMode = False

要显示特定的所有数据(重置过滤条件) Worksheet

If Workbook("WorkbookName").Worksheets("SheetName").FilterMode Then 
    Workbook("WorkbookName").Worksheets("SheetName").ShowAllData
EndIf

浏览每个 Worksheet Workbook

Dim ws as Worksheet
For Each ws in Workbook("WorkbookName").Worksheets  
    ws.AutoFilterMode = False '(can be replaced with .ShowAllData as in example above)  
Next

详细说明 Worksheets

Dim ws as Worksheet  
For Each ws in Workbook("WorkbookName")  
    If InStr(1,"Sheet1Sheet2Sheet3Sheet4",ws.Name, 0) > 0 Then
        ws.AutoFilterMode = False
    EndIf
Next

如果您只使用一个Workbook,则可以省略Workbook("WorkbookName") 如果您需要参考执行宏的Workbook,请将Workbook("WorkbookName")更改为ThisWorkbook  !以下代码仅适用于 .ShowAllData
保存过滤器标准(在重置标准之前执行):

Dim ws As Worksheet, i As Long, j As Long, x As Long, arrFCriteria(), Item As Filter
x = ThisWorkbook.Worksheets.Count
ReDim arrFCriteria(1 To x, 1 To 1)
i = 1    
For Each ws in ThisWorkbook.Worksheets
    j = 1  
    If ws.FilterMode Then
        For Each Item in ws.AutoFilter.Filters 
            If ws.AutoFilter.Filters.Count > UBound(arrFCriteria, 2) Then ReDim Preserve arrFCriteria(1 To x, 1 To ws.AutoFilter.Filters.Count) 
            If Item.On Then  
                arrFCriteria(i,j) = Item.Criteria1  
            Else
                arrFCriteria(i,j) = 0
            EndIf  
            j = j + 1 
        Next  
    EndIf  
    i = i + 1
Next

其中arrFCriteria是带有存储过滤条件的二维数组 可以使用索引恢复过滤器(第一维是Worksheets()的索引,第二维是.AutoFilter.Filters().Criteria1的索引。)
要恢复过滤器(最后添加):

For i = LBound(arrFCriteria, 1) To UBound(arrFCriteria, 1)  
    j = 1  
    If Not ThisWorkbook.Worksheets(i).AutoFilter Is Nothing Then  
        For Each Item In ThisWorkbook.Worksheets(i).AutoFilter.Filters  
            If arrFCriteria(i, j) <> 0 Then  
                ThisWorkbook.Worksheets(i).AutoFilter.Range.AutoFilter Field:=j, Criteria1:=arrFCriteria(i, j)  
            End If  
            j = j + 1
        Next  
    End If  
Next i

基本上你的代码看起来像这样:

Sub MyMacro ()
    'Part0 (variable declaration, make sure to include those I wrote)
    'Part1 (saving criterias)
    'Part2 (loop through worksheets, reset filter)
    'Part3 (your macro code)
    'Part4 (restoring filters)
End Sub