White
White

Reputation: 111

Sort predetermined fields with a macro

I would like to sort my table depending on five parameters. I have the following columns:

Sorted in this order:

  1. Data
  2. Zeitraster
  3. Botschaftzahl
  4. Richtung
  5. LSB Position

Upvotes: 0

Views: 63

Answers (2)

user4039065
user4039065

Reputation:

VBA will only allow three keys to sort on in any one process. If more than three keys are required, you sort the last keys first and then return to the three most primary keys.

Sub custom_sort()
    Dim vKEYs As Variant
    vKEYs = Array("Data", "Zeitraster", "Botschaftzahl", "Richtung", "LSB Position")
    With ActiveSheet
        With .Cells(1, 1).CurrentRegion
            .Cells.Sort Key1:=.Columns(Application.Match(vKEYs(3), .Rows(1), 0)), Order1:=xlAscending, _
                        Key2:=.Columns(Application.Match(vKEYs(4), .Rows(1), 0)), Order2:=xlAscending, _
                        Orientation:=xlTopToBottom, Header:=xlYes
            .Cells.Sort Key1:=.Columns(Application.Match(vKEYs(0), .Rows(1), 0)), Order1:=xlAscending, _
                        Key2:=.Columns(Application.Match(vKEYs(1), .Rows(1), 0)), Order2:=xlAscending, _
                        Key3:=.Columns(Application.Match(vKEYs(2), .Rows(1), 0)), Order3:=xlAscending, _
                        Orientation:=xlTopToBottom, Header:=xlYes

        End With
    End With
End Sub

That uses the data block starting in A1. It uses the application.Match across the header row to get the position of each sort key column.

Upvotes: 1

PaulG
PaulG

Reputation: 1189

You can use Data=>Sort which will bring up a dialog box to allow you to do that. In VBA you can invoke the Sort function.

ActiveWorkbook.Worksheets("Sheet1").Sort....

Easiest way to do this would actually be to record it and all should become clear.

Upvotes: 0

Related Questions