自动过滤后的VBA复制范围

时间:2018-03-13 07:58:14

标签: excel vba excel-vba

我想在autofilter函数工作后复制表,如下面的代码。我尝试了几种方法,但没有奏效。如何在自动过滤后过滤唯一可见的单元格(表格)?

ActiveSheet.Range("$K$9:$K$1000").AutoFilter Field:=1, Criteria1:="Hatalı", Operator:=xlAnd

1 个答案:

答案 0 :(得分:2)

您可以使用Range.SpecialCells Method仅获取范围内的可见单元格。

ActiveSheet.Range("$K$9:$K$1000").SpecialCells(xlCellTypeVisible).Copy Worksheets("destination").Range("A1")

注意:如果在此范围内没有可见的单元格,则会抛出错误。因此,您可能希望在复制之前先检查它。

Dim FilteredRange As Range

On Error Resume Next 'disable error reporting, below line throws an error if no cells are visible in that range
Set FilteredRange = ActiveSheet.Range("$K$9:$K$1000").SpecialCells(xlCellTypeVisible)
On Error GoTo 0 'enable error reporting

If Not FilteredRange Is Nothing Then
    'copy filtererd range if there are visible cells
    FilteredRange.Copy Worksheets("destination").Range("A1")
Else
    MsgBox "The filtered range is empty"
End If