Question

I am trying to create a code which automatically sorts a column when I add a new value at the bottom or change an existing value. So I have values ranging from E3:E210; and if I add or change a value at E211. I want it to automatically sort that range (E3:E210) or if I change a value at E205. I also want it to go to the cell that it was sorted to (if possible). So If I add a value at E211 and it sort to let's say E150. I want it to select that cell so I basically stay on that cell.

This is all the code I am running on the sheet:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

Dim Rng As Range
Set Rng = Range(Cells(3, 6), Cells(500, 7))
Dim Intersection
Set Intersection = Application.Intersect(Target, Rng)

If Target.Cells.Count = 1 Then
    If Not Intersect(Target, [B2]) Is Nothing Then _
        Range("E:E").Find(vbNullString, [E3], , , , xlNext).Select
End If

If Not Intersection Is Nothing Then
    If IsNumeric(Selection.Value) And Selection.Value <> "" Then
        If (GetAsyncKeyState(vbKeyRButton)) Then 'right mouse button
            Selection.Value = (Selection.Value + 1)
            Cells(Selection.Row, 1).Select
        End If
    End If
End If

End Sub

Private Sub Worksheet_BeforeRightClick(ByVal Target As Range, Cancel As Boolean)
    Dim Rng As Range
    Set Rng = Range(Cells(3, 6), Cells(500, 7))
    Dim Intersection
    Set Intersection = Application.Intersect(Target, Rng)

    If Not Intersection Is Nothing Then
    Cancel = True
    End If
End Sub

Private Sub Worksheet_Change(ByVal Target As Range)
Target.EntireColumn.Sort Key1:=Target, Order1:=xlAscending, Header:=xlGuess, OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom
End Sub

The last part is my attempt to do autosort (with the help of forums). It does sort the values. But it does not sort a certain range and it does not stay on the cell. If anyone can help, much appreciated!

Was it helpful?

Solution

If you want to automatically sort on any change in the column, something like:

Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
    Dim myRng As Range
    Dim S As String
Set myRng = Cells.Columns(5) '<--change to column you want to sort
If Not Intersect(Target, myRng) Is Nothing Then
    Application.EnableEvents = False
    S = Target.Text
    myRng.Resize(columnsize:=3).Sort key1:=myRng, order1:=xlAscending, Header:=xlNo, Orientation:=xlSortColumns
    myRng.Find(what:=S, LookIn:=xlValues, lookat:=xlWhole, MatchCase:=True).Select
    Selection.Show
    Application.EnableEvents = True
End If

End Sub

(I am not entirely certain that the .Show statement is required).

EDIT: changed to sort columns E:G together

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top