删除范围并在多个选项卡中创建自动筛选

时间:2017-01-23 17:47:34

标签: excel vba excel-vba

我想编写一个宏来创建AutoFilter,如果不存在,则删除过滤器并删除工作簿中某些选项卡中的特定范围。

我创建了这段代码,但不管怎么说它都不起作用 - 数据gis只从一个标签中删除,而不是在If语句中没有列出的所有标签。请帮忙!

Sub ClearTabs()

Dim rng As Range
Dim ws As Worksheet
Set rng = Range("B9:AK100")

For Each ws In ThisWorkbook.Sheets
    If ws.Name <> "lastfile" And ws.Name <> "Sheet1" And ws.Name <> "Sheet2" Then

        If Not ws.AutoFilterMode Then
            ws.Range("B8:AK8").AutoFilter
        End If
    ws.AutoFilter.ShowAllData
    rng.ClearContents

    End If

Next ws

End Sub

2 个答案:

答案 0 :(得分:1)

按照上面的评论,你需要在Set rng = Range("B9:AK100")循环中设置范围(For Each ws In ThisWorkbook.Sheets)。

<强>代码

Sub ClearTabs()

Dim rng As Range
Dim ws As Worksheet

For Each ws In ThisWorkbook.Sheets
    With ws
        Select Case .Name
            Case "lastfile", "Sheet1", "Sheet2"
                ' do nothing
            Case Else
                Set rng = .Range("B9:AK100")

                If Not .AutoFilterMode Then
                    .Range("B8:AK8").AutoFilter
                End If
                .AutoFilter.ShowAllData
                rng.ClearContents
        End Select
    End With
Next ws

End Sub

答案 1 :(得分:0)

你可以避免变暗和设置rng并像这样

Option Explicit

Sub ClearTabs()
    Dim ws As Worksheet

    For Each ws In ThisWorkbook.Sheets
        With ws
            If .Name <> "lastfile" And .Name <> "Sheet1" And .Name <> "Sheet2" Then
                If .AutoFilterMode Then
                    .AutoFilter.ShowAllData
                Else
                    .Range("B8:AK8").AutoFilter
                End If
                .Range("B9:AK100").ClearContents
            End If
        End With
    Next
End Sub