首页 > 解决方案 > 从过滤器中清除表格的 ShowAllData excel 宏在脚本中给出错误 9

问题描述

我有一个按钮,可以将源表中的一些列复制/粘贴到新表/工作表中,这可以正常工作,除非源表被过滤。如果我以某种方式留下了一些过滤器,它不会复制所有数据:(

我已经尝试了“ShowAllData”的几种组合,但仍然全部失败,并出现相同的错误 '9' OutOfScript ......这是我的整个代码:

Sub Button1_Click()
    Dim row_last As Long
    Dim range_src As String
    Dim cols_src As Variant

    cols_src = Array("A", "B", "C", "D", "I", "R", "S", "T", "U")
    Sheets("TMP").Cells.Clear

    With Sheets("Validation by rules")
        ' Set lo = .ListObjects(1)
        ' lo.AutoFilter.ShowAllData
        ' Sheets("Validation by rules").ListObjects(1).AutoFilter.ShowAllData
        ' ActiveSheet.ListObjects(1).AutoFilter.ShowAllData
        row_last = .Cells(.Rows.Count, 1).End(xlUp).Row
        Dim i As Long
        For i = LBound(cols_src) To UBound(cols_src)
            ' MsgBox .Cells(1, cols_src(i))
            .Range(.Cells(1, cols_src(i)), .Cells(row_last, cols_src(i))).Copy Destination:=Sheets("TMP").Cells(1, i + 1)
        Next i
    End With
    MsgBox CStr(row_last) & " records copied"
    ThisWorkbook.RefreshAll
End Sub

任何提示,关于我做错了什么......谢谢!

标签: vbaexcel

解决方案


首先,使用 ListObject 对象的 ShowAutoFilter 属性检查是否显示自动过滤器,然后显示所有数据,如果它处于过滤器模式。

Dim lo As ListObject

With Sheets("Validation by rules")
    Set lo = .ListObjects(1)
    With lo
        If .ShowAutoFilter Then
            With .AutoFilter
                 If .FilterMode Then .ShowAllData
            End With
        End If
    End With
    'etc
    '
    '
    '
End With

推荐阅读