this might be easier to change if your ranges change:
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Dim Rng1 As Range
Dim Rng2 As Range
Dim Rng1Key As Range
Dim Rng2Key As Range
If Target.Cells.Count > 1 Then Exit Sub
Set Rng1 = Me.Range("n9:v16")
Set Rng2 = Me.Range("n20:v27")
'just gonna check one of the key columns.
'if you change anything else, it won't affect the sort
Set Rng1Key = Me.Range("v9:v16,p9
16,u9:u16")
Set Rng2Key = Me.Range("v20:v27,p20
27,u20:u27")
On Error GoTo errHandler:
If Not (Intersect(Target, Rng1Key) Is Nothing) Then
'it's in one of the keys in rng1
Application.EnableEvents = False
Rng1.Sort key1:=Me.Range("v9"), order1:=xlDescending, _
key2:=Me.Range("p9"), order2:=xlDescending, _
key3:=Me.Range("u9"), order3:=xlDescending, _
header:=xlNo, OrderCustom:=1, _
MatchCase:=False, Orientation:=xlTopToBottom
ElseIf Not (Intersect(Target, Rng2Key) Is Nothing) Then
Rng2.Sort key1:=Me.Range("v9"), order1:=xlDescending, _
key2:=Me.Range("p9"), order2:=xlDescending, _
key3:=Me.Range("u9"), order3:=xlDescending, _
header:=xlNo, OrderCustom:=1, _
MatchCase:=False, Orientation:=xlTopToBottom
End If
errHandler:
Application.EnableEvents = True
End Sub
=====
But sorts are very forgiving. You can tell excel that the key is A1 and it'll
use all of column A.
And if the keys are the same (V,P,U), then you could condense the code:
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Dim Rng1 As Range
Dim Rng2 As Range
Dim Rng1Key As Range
Dim Rng2Key As Range
Dim SortRng As Range
If Target.Cells.Count > 1 Then Exit Sub
Set Rng1 = Me.Range("n9:v16")
Set Rng2 = Me.Range("n20:v27")
'just gonna check one of the key columns.
'if you change anything else, it won't affect the sort
Set Rng1Key = Me.Range("v9:v16,p9
16,u9:u16")
Set Rng2Key = Me.Range("v20:v27,p20
27,u20:u27")
On Error GoTo errHandler:
If Intersect(Target, Application.Union(Rng1Key, Rng2Key)) Is Nothing Then
Exit Sub
End If
If Intersect(Target, Rng1Key) Is Nothing Then
Set SortRng = Rng2
Else
Set SortRng = Rng1
End If
Application.EnableEvents = False
SortRng.Sort key1:=Me.Range("v1"), order1:=xlDescending, _
key2:=Me.Range("p1"), order2:=xlDescending, _
key3:=Me.Range("u1"), order3:=xlDescending, _
header:=xlNo, OrderCustom:=1, _
MatchCase:=False, Orientation:=xlTopToBottom
errHandler:
Application.EnableEvents = True
End Sub
====
And the application.enableevents seems to be overkill. The worksheet_change
event didn't fire with a sort.