Sorting the cell addresses of a union with
ascending row and descending column
Straight forward approach using the inbuilt sort of Excel:
Option Explicit
Sub sort_union()
Dim myRange As Range
Dim myCell As Range
Dim iCt As Integer
Dim maxCt As Integer
On Error Resume Next
Application.DisplayAlerts = False
Sheets("RangeSort").Delete
Application.DisplayAlerts = True
On Error GoTo 0
Worksheets.Add.Name = "RangeSort"
Set myRange = Union(Range("$E$12"), Range("$B$11:$C$12"), _
Range("$G$14"), Range("$F$2"), Range("$F9"))
Debug.Print vbCrLf & "ORIGINAL:"
Debug.Print myRange.Address
iCt = 1
Range("A1") = "Address"
Range("B1") = "Row"
Range("C1") = "Column"
For Each myCell In myRange
Range("A1").Offset(iCt, 0) = myCell.Address
Range("B1").Offset(iCt, 0) = myCell.Row
Range("C1").Offset(iCt, 0) = myCell.Column
iCt = iCt + 1
Next myCell
maxCt = iCt - 1
Call SortCurrentRegion
Set myRange = Range(Range("A2").Value)
'Debug.Print iCt; myRange.Address
'create sorted union
For iCt = 2 To maxCt
Set myRange = Union(myRange, Range(Range("A1").Offset(iCt, 0)))
Debug.Print iCt; myRange.Address
Next iCt
Debug.Print vbCrLf & "SORTED:"
Debug.Print myRange.Address
'Delete Sheet "RangeSort"
'On Error Resume Next
'Application.DisplayAlerts = False
'Sheets("RangeSort").Delete
'Application.DisplayAlerts = True
'On Error GoTo 0
End Sub
Sub SortCurrentRegion()
Dim sortRange As Range
Set sortRange = ActiveSheet.Range("A1").CurrentRegion
With ActiveSheet.Sort
.SortFields.Clear
'sort "Col B" = "Row" ascending
.SortFields.Add2 Key:=Range("B1"), SortOn:=xlSortOnValues, _
Order:=xlAscending, DataOption:=xlSortNormal
'sort "Col C" = "Column" descending
.SortFields.Add2 Key:=Range("C1"), SortOn:=xlSortOnValues, _
Order:=xlDescending, DataOption:=xlSortNormal
.SetRange Range("A1").CurrentRegion
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub
Here the output of the Immediate Window:
ORIGINAL:
$E$12,$B$11:$C$12,$G$14,$F$2,$F$9
SORTED:
$F$2,$F$9,$E$12,$B$11:$C$12,$G$14
Why is $E$12 in front of $B$11:$C$12?
In the output of the Immediate Window we see that by adding address $C$11 to the union the range $B$11:$C$12 changes to the end of the union! ;-(
ORIGINAL:
$E$12,$B$11:$C$12,$G$14,$F$2,$F$9
2 $F$2,$F$9
3 $F$2,$F$9,$C$11
4 $F$2,$F$9,$B$11:$C$11
5 $F$2,$F$9,$B$11:$C$11,$E$12
6 $F$2,$F$9,$B$11:$C$11,$E$12,$C$12
7 $F$2,$F$9,$E$12,$B$11:$C$12
^^-- $C$11 is added to the union here
8 $F$2,$F$9,$E$12,$B$11:$C$12,$G$14
^^-- $B$11:$C$12 moved to the end of the union automatically
SORTED:
$F$2,$F$9,$E$12,$B$11:$C$12,$G$14