0

I am trying to automatically sort the sheet "Sortable" when values are entered into column E on the tab "Data". I have the following code on the Data Sheet, but it still sorts Data, not Sortable.

Private Sub Worksheet_Change(ByVal Target As Range)
    On Error Resume Next
    If Not Intersect(Target, Range("E:E")) Is Nothing Then
        Sheets(“Sortable”).Select
            Range("E1").Sort Key1:=Range("E2"), _
                Order1:=xlAscending, Header:=xlYes, _
                OrderCustom:=1, MatchCase:=False, _
                Orientation:=xlTopToBottom
    End If
End Sub
braX
  • 11,506
  • 5
  • 20
  • 33

1 Answers1

1

Some suggestions:

1- Be careful using Activate (see this post)

2- Don't hide errors with On error resume next unless is strictly necessary

3- Regarding the code:

  • I've defined some objects at the begining of the code so it's clear what you're working with.
  • Read the comments and customize it to fit your needs

Let me know if it works!

Private Sub Worksheet_Change(ByVal Target As Range)

    ' Declare objects

    Dim sortableWorkSheet As Worksheet
    Dim monitoredRange As Range
    Dim sortableRange As Range
    Dim sortableFieldCell As Range

    ' Adjust this variables to fit your needs

    Set monitoredRange = Me.Range("E:E")
    Set sortableWorkSheet = ThisWorkbook.Worksheets("Sortable")
    Set sortableRange = sortableWorkSheet.Range("E1")
    Set sortableFieldCell = sortableWorkSheet.Range("E1")


    If Not Intersect(Target, monitoredRange) Is Nothing Then

        ' Sort range
        sortableRange.Sort _
            Key1:=sortableFieldCell, _
            Order1:=xlAscending, _
            Header:=xlYes, _
            OrderCustom:=1, _
            MatchCase:=False, _
            Orientation:=xlTopToBottom

    End If

End Sub
Ricardo Diaz
  • 5,658
  • 2
  • 19
  • 30