Error when I use SpecialCells of AutoFilter to get visible cells in VBA

白昼怎懂夜的黑 提交于 2019-11-29 05:06:03

To work with the visible cells of an AutoFilter, you have to use Offset if you are planning to exclude Headers. The error you are getting is because you are missing a "." before Cells(2,11)

'~~> Remove any filters
ActiveSheet.AutoFilterMode = False

'~~> Filter, 
With rRange 
  .AutoFilter Field:=1, Criteria1:=strCriteria

  '~~> offset(to exclude headers)
  Debug.Print .Offset(1, 0).SpecialCells(xlCellTypeVisible).Cells(2,11).Value

  Debug.Print .SpecialCells(xlCellTypeVisible).Cells(2,11).Value
End With

'~~> Remove any filters
ActiveSheet.AutoFilterMode = False

I decided to add this as a part of this answer so that it might help someone else in the future.

Let's say our range is

A1:F6

When you run the below code, depending on whether you are using Offset or not, you will get these results.

Option Explicit

Sub Sample()
    '~~> Remove any filters
    ActiveSheet.AutoFilterMode = False

    Dim rRange As Range
    Dim Rnge As Range

    Set rRange = Sheets("Sheet1").Range("A1:F6")

    '~~> Filter,
    With rRange
      .AutoFilter Field:=1, Criteria1:="<>2"

      '~~> Offset(to exclude headers)
      Set Rnge = .Offset(1, 0).SpecialCells(xlCellTypeVisible)

      Debug.Print Range(Rnge.Address).Address
      Debug.Print ActiveSheet.Cells(3, 2).Address
      Debug.Print Range(Rnge.Address).Cells(3, 2).Address

      Debug.Print "--------------------------------------------------"

      '~~> To include headers
      Set Rnge = .SpecialCells(xlCellTypeVisible)

      Debug.Print Range(Rnge.Address).Address
      Debug.Print ActiveSheet.Cells(3, 2).Address
      Debug.Print Range(Rnge.Address).Cells(3, 2).Address

    End With

    '~~> Remove any filters
    ActiveSheet.AutoFilterMode = False
End Sub

HTH

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!