Get a filtered range into an array

后端 未结 2 1016
别跟我提以往
别跟我提以往 2021-01-23 18:30

I am trying to get a filtered range into an array, on my test data the array fArr has the proper dim and fLR is the proper count of the filter range

But filRange is alwa

2条回答
  •  盖世英雄少女心
    2021-01-23 19:08

    Perhaps your data has more complexity, but you can simply assign the values of a range to an array with:

    var = rng.SpecialCells(xlCellTypeVisible).Value
    

    Thus no need to loop over the data.

    Here's a working example with this simple grid of data:

    This code:

    Option Explicit
    
    Sub arrFilterdRng()
    
        Dim ws As Worksheet '<-- your worksheet
        Dim rng As Range    '<-- your range to filter
        Dim var As Variant  '<-- will hold array of visible data
        Dim lng1 As Long, lng2 As Long
    
        ' get sheet; remove filters
        Set ws = ThisWorkbook.Worksheets("Sheet2")
        ws.AutoFilterMode = False
    
        ' get range; apply filter
        Set rng = ws.UsedRange
        rng.AutoFilter Field:=1, Criteria1:="x"
    
        ' assign visible range to array
        var = rng.SpecialCells(xlCellTypeVisible).Value
    
        ' test array
        For lng1 = LBound(var, 1) To UBound(var, 1)
            For lng2 = LBound(var, 2) To UBound(var, 2)
                Debug.Print var(lng1, lng2)
            Next lng2
        Next lng1
    
    End Sub
    

    Results in this on the sheet:

    And the output to the Immediate window for the content of var is:

    a
    b
    c
    x
     2 
     3 
    x
     5 
     6 
    

提交回复
热议问题