Option Explicit
Sub F_____gMacro()
'
' constants
Const ksRangeAll = "A5:B13"
Const kiColorColumn = 1
Const kiOrderColumn = 2
Const kiOrder = xlAscending
'
' declarations
Dim rngAll As Range, rngSel As Range, rngSrt As Range
Dim lBaseRow As Long, lMovedRows As Long
Dim I As Long, J As Long
'
' start
' ranges
Set rngAll = Range(ksRangeAll)
Set rngSel = Application.Intersect(Selection, rngAll)
' valid selection
If rngSel Is Nothing Then
Exit Sub
Else
If rngSel.Cells.Count = 1 And rngSel.Cells(1, 1).Value = "" Or _
rngSel.Rows.Count > 1 Then Exit Sub
End If
' initial rows
lBaseRow = rngSel.Row - rngAll.Row + 1
lMovedRows = 0
'
' process
With rngAll
' move
For I = lBaseRow + 1 To .Rows.Count
If .Cells(I, kiColorColumn).Interior.ColorIndex <> xlNone Then
J = lBaseRow + lMovedRows + 1
If I <> J Then
lMovedRows = lMovedRows + 1
.Rows(I).Cut
.Rows(J).Insert Shift:=xlShiftDown
End If
End If
Next I
' sort
If lMovedRows > 0 Then
Set rngSrt = Range(.Rows(lBaseRow + 1), .Rows(lBaseRow + lMovedRows))
rngSrt.Sort Key1:=.Columns(kiOrderColumn), Order1:=kiOrder, Header:=xlNo
Set rngSrt = Nothing
End If
End With
'
' end
' positioning
rngAll.Cells(1, 1).Select
' ranges
Set rngSel = Nothing
Set rngAll = Nothing
' beep
Beep
'
End Sub