Search code examples
excelvbaexcel-2007listobject

Array with data from filtered and ordered listobject in excel 2007 vba


Good morning to all, I have a listobject with 17 fields and some rows (10-20 rows) and I need to filter the listobject for any distinct value I find in a column. This filtered listobject has to be ordered in ascending order by another integer column and then I have to find data not in sequence and get minimum and maximum value of the consecutive numbers.

To get the unique values I've written this function that works well:

    Public Function GetUnique(Inputrange As Range)

    Dim d As Object, c As Range, k, tmp As String

    Set d = CreateObject("scripting.dictionary")
    For Each c In Inputrange
        tmp = Trim(c.Value)
        If Len(tmp) > 0 Then d(tmp) = d(tmp) + 1
    Next c
    GetUnique = d.Keys
End Function

To filter data and sort filtered data I'm trying to use this code

Dim tblaux as listobject
Dim RdS as variant
Dim r as variant

With tblaux
        Z = GetUnique(.ListColumns(7).DataBodyRange)
        For Each RdS In Z
            .Range.AutoFilter Field:=7, Criteria1:="=" & RdS
            .Sort.SortFields.Clear
            .Sort.SortFields.Add Key:=.Range.Columns(1), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
            With .Sort
                .Header = xlYes
                .MatchCase = False
                .Orientation = xlTopToBottom
                 Set r = .rng.Offset(1, 0).Resize(.rng.Rows.Count - 1, .rng.Columns.Count).SpecialCells(xlCellTypeVisible)
            End With
    Next RdS
End with

What I get from this code should be an array with the filtered and sorted data but what I get is made with a number of areas correesponing to non contiguous lines in the table.

I'm going a sligtly mad but I can't solve this issue.

Thanks for support


Solution

  • edited after OP's clarification he wanted a contiguous range filtered

    Option Explicit
    
    Sub main()
        Dim tblaux As ListObject
        Dim RdS As Variant, Z As Variant
        Dim r As Variant
    
        With Worksheets("tblaux").ListObjects("tblaux")
            Z = GetUnique(.ListColumns(7).DataBodyRange)
            With .Range
                For Each RdS In Z
                    .Sort key1:=.Range("G1"), order1:=xlAscending, key2:=.Range("A1"), order2:=xlAscending, Header:=xlYes, Orientation:=xlTopToBottom, MatchCase:=False
                    .AutoFilter Field:=7, Criteria1:="=" & RdS
                    MsgBox .Offset(1, 0).Resize(.Rows.Count - 1, .Columns.Count).SpecialCells(xlCellTypeVisible).Address
                    r = .Offset(1, 0).Resize(.Rows.Count - 1, .Columns.Count).SpecialCells(xlCellTypeVisible).Value
                Next RdS
            End With
        End With
    End Sub