Reputation: 29
i have a sheet which is populated by another sheet and in the populated sheet i want to do an automatic sort in an ascending order but every time data enter, i sorts even my columns and the values i don't want it to sort as below:
i want it it sort column AK starting from cell AK3 while excluding X which are just there to keep the cells. The data which is (DIV 3,DIV 2,DIV 1,DIV 4) is picked from another worksheet. I want it to sort beginning with DIV 1 to DIV 4,
Private Sub Worksheet_Change(ByVal Target As Range)
On Error Resume Next
If Not Intersect(Target, Range("AK:AK")) Is Nothing Then
With ThisWorkbook
Range("AK1").Sort Key1:=Range("AK3"), _
Order1:=xlAscending, Header:=xlYes, _
OrderCustom:=1, MatchCase:=False, _
Orientation:=xlTopToBottom
End With
End If
End Sub
Upvotes: 0
Views: 64
Reputation: 42236
Please, copy the next event code instead of the existing one (Worksheet_Change
):
Option Explicit
Private Sub Worksheet_Calculate()
Dim lastR As Long
lastR = Me.Range("C" & Me.rows.count).End(xlUp).row
With Me
.Range("AK3:AK" & lastR).Calculate
Application.EnableEvents = False
On Error GoTo NiceEnding
.Sort.SortFields.Clear
.Sort.SortFields.Add2 key:=.Range("AK3:AK" & lastR), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortNormal
With .Sort
.SetRange Me.Range("A3:AK" & lastR)
.Header = xlNo
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End With
NiceEnding:
Application.EnableEvents = True
End Sub
The above event is triggered by any formula result change, which triggers the Calculate
event.
If you really need/want to do the job only if changes are done in "AK:AK" column, a Private
array variable will keep all values of the respective range and when the event is triggered the column cells are compared with the array values and the sorting is executed only if any cell value has been changed. Then the new values in that column are loaded in the reference array. But, in such a case sorting will not do anything, keeping existing order...
Upvotes: 1