Home » excel » excel – Encountering a problem in my code to do multi level sorting

excel – Encountering a problem in my code to do multi level sorting

Posted by: admin May 14, 2020 Leave a comment

Questions:

Trying to do this multi level sorting by copying the code from this link. I have only pasted the relevant code here

https://trumpexcel.com/sort-data-vba/

Public DestinationShVar as Worksheet
Public wDestination as workbook
  For Each sht In wDestination.Worksheets
  If sht.Name Like "*-*" Then Set DestinationShVar = sht
Next sht

With DestinationShVar.Sort
.SortFields.Add Key:=Range("AK1"), Order:=xlDescending
.SortFields.Add Key:=Range("B1"), Order:=xlAscending
.SetRange Range("A:GB")
.Header = xlYes
.Apply
End With

I am getting an error of

Object variable not set on

With DestinationShVar.Sort

Would anyone know why?

How to&Answers:

The Public Issue

  • The error might have occurred because you didn’t declare the sht
    variable.
  • You have to include the filter in the loop, otherwise it will loop
    through the worksheets and apply the filter only to the last found
    worksheet.
  • You cannot declare a variable as Public inside of a procedure,
    you have to use Dim (or Static).

The Code

Sub PublicIssue1()


    Dim WDestination As Workbook
    Dim sht As Worksheet

    Set WDestination = Worksbooks("Boo1.xls")

    For Each sht In WDestination.Worksheets

        If sht.Name Like "*-*" Then

            With sht.Sort
                .SortFields.Add Key:=Range("AK1"), Order:=xlDescending
                .SortFields.Add Key:=Range("B1"), Order:=xlAscending
                .SetRange Range("A:GB")
                .Header = xlYes
                .Apply
            End With

        End If

    Next sht

End Sub

If you are declaring a variable as Public, it has to be before all procedures in a module.

Public WDestination as Workbook

Sub PublicIssue2()

    Dim sht As Worksheet

    'Set WDestination = Worksbooks("Boo1.xls") ' If it is not set.

    For Each sht In WDestination.Worksheets

        If sht.Name Like "*-*" Then

            With sht.Sort
                .SortFields.Add Key:=Range("AK1"), Order:=xlDescending
                .SortFields.Add Key:=Range("B1"), Order:=xlAscending
                .SetRange Range("A:GB")
                .Header = xlYes
                .Apply
            End With

        End If

    Next sht

End Sub