VBA:如何从过滤后的数据中获取当前区域?

时间:2017-08-08 12:36:11

标签: vba excel-vba range filtering variant

我想知道如何在过滤到变体对象后获取数据。当我使用它时:

table = ActiveSheet.Range("A1").CurrentRegion

我喜欢所有数据,但我只想过滤。

工作簿屏幕截图: enter image description here

2 个答案:

答案 0 :(得分:4)

您可以使用SpecialCells(xlCellTypeVisible)获取已过滤的行:

Dim Tbl As Range

Set Tbl = ActiveSheet.Range("A1").CurrentRegion.SpecialCells(xlCellTypeVisible)
' for DEBUG onlu
Debug.Print Tbl.Address

修改1 :完整代码

Option Explicit

Sub VarfiltRange()

Dim BasketCostFiltRng As Range
Dim LastRow As Long
Dim VarRes As Double

With Worksheets("Sheet1") '< -- modift "Sheet1" to your sheet's name
    LastRow = .Cells(.Rows.Count, "D").End(xlUp).Row

    ' get only the filteres rows in column D
    Set BasketCostFiltRng = .Range("D2:D" & LastRow).SpecialCells(xlCellTypeVisible)

    ' get the variance of only visible cells in Column "D" (after you filter to show only 1100 and 1112 in column "A")
    VarRes = WorksheetFunction.Var(BasketCostFiltRng)
    MsgBox VarRes
End With

End Sub

答案 1 :(得分:2)

您可以使用SpecialCells来获取该内容:

Sheet1.AutoFilter.Range.SpecialCells(xlCellTypeVisible).Address