Search code examples
excelvba

Ordering data on a set column on four sheets in a single workbook


This program is supposed to order dates in descending order from N14 to N66.

The program works as intended on the first sheet but not on the other three. The specified area is the same on all four sheets (N14 - N66) and the data to arrange is dates on all four sheets.

I attempted to place the code for each individual sheet, this had the same result.
I tried looping it for sheets 2-4.

I looked at a similar problem VBA-Excel macro only works on current sheet.
I get

Compile Error: Invalid or unqualified reference

The main program is in a module as a subroutine called "OrderDates" (program below). This subroutine is called for each sheet (in "Microsoft Excel Objects Folder"). Using this structure, the program works as intended on the 1 sheet only.

Sub OrderDates()
    On Error Resume Next
    If Not Intersect(Target, Range("N:N")) Is Nothing Then
        Range("N14").Sort key1:=Range("N66"), _
          Order1:=xlAscending, Header:=xlNo, _
          OrderCustom:=1, MatchCase:=True, _
          Orientation:=xlTopToBottom
    End If
End Sub

Calling the subroutine when a change is made to the worksheet (this is called for each sheet separately in the Microsoft excel Objects folder).

Private Sub Worksheet_Change(ByVal Target As Range)
    Call OrderDates
End Sub

Solution

  • Please, try the next adapted solution. Not answering my clarification question, the solution assumes that the four sheets in discussion contain a similare Event code and you want the called Sub processing the respective triggered event sheet. The called common Sub must have a parameter to know where from the call came:

    Sub OrderDates(Target as Range)
        dim ws as Worksheet
        set ws = Target.parent
        If Not Intersect(Target, ws.Range("N:N")) Is Nothing Then
            ws.Range("N14").Sort key1:=ws.Range("N66"), _
            Order1:=xlAscending, Header:=xlNo, _
            OrderCustom:=1, MatchCase:=True, _
            Orientation:=xlTopToBottom
        End If
    End Sub
    

    Range("N:N") refers the active sheet and it must be fully qualified.

    The Event code should look as:

    Private Sub Worksheet_Change(ByVal Target As Range)
      Application.EnableEvents = False
        OrderDates Target
      Application.EnableEvents = True
    End Sub
    

    To 'inform' the called sub what range should be processed...