Excel VBA - Apply auto filter and Sort by specific colour

前端 未结 1 376
傲寒
傲寒 2021-01-21 18:34

I have an auto-filtered range of data. The auto filter was created by the following VB code:

Sub Colour_filter()

Range(\"A4\").Select
Range(Selection, Selection         


        
1条回答
  •  后悔当初
    2021-01-21 19:20

    Well here is a small Sub that does the following sorting as per shown image. Most of the values like dimensions/range sizes are very static since this is a sample. You may improve it to be dynamic. Please comment if this code is going in the right direction so I can update with the final sort.

    EDITTED CODE WITH DOUBLE SORT KYES

    code: Option Explicit

    Sub sortByColor() Dim rng As Range
    Dim i As Integer Dim inputArray As Variant, colourSortID As Variant Dim colourIndex As Long

    Set rng = Sheets(1).Range("D2:D13")
    colourIndex = Sheets(1).Range("G2").Interior.colorIndex
    
     ReDim inputArray(1 To 12)
     ReDim colourSortID(1 To 12)
    
    For i = 1 To 12
        inputArray(i) = rng.Cells(i, 1).Interior.colorIndex
        If inputArray(i) = colourIndex Then
            colourSortID(i) = 1
        Else
            colourSortID(i) = 0
        End If
    Next i
    
    '--output the array with colourIndexvalues and sorting key values
     Sheets(1).Range("E2").Resize(UBound(inputArray) + 1) = _ 
                       Application.Transpose(inputArray)
     Sheets(1).Range("F2").Resize(UBound(colourSortID) + 1) = _ 
                       Application.Transpose(colourSortID)
    
     '-sort the rows based on the interior colour
     Application.DisplayAlerts = False
     Set rng = rng.Resize(, 3)
    
        rng.Sort Key1:=Range("F2"), Order1:=xlDescending, _
        Key2:=Range("E2"), Order1:=xlAscending, Header:=xlNo, _
        OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
        DataOption1:=xlSortNormal
    
     Application.DisplayAlerts = True
    
     End Sub
    

    output:

    enter image description here

    0 讨论(0)
提交回复
热议问题