Excel 在执行多级排序的代码中遇到问题

Excel 在执行多级排序的代码中遇到问题,excel,vba,Excel,Vba,尝试通过复制此链接中的代码来执行此多级排序。我只在这里粘贴了相关代码 我犯了一个错误 对象变量未设置为on 有人知道为什么吗?公共问题 发生错误的原因可能是您没有声明sht 变数 必须在循环中包含过滤器,否则它将循环 浏览工作表并仅对最后找到的应用过滤器 工作表 不能在过程内部将变量声明为Public, 您必须使用Dim(或Static) 代码 如果要将变量声明为Public,则它必须位于模块中所有过程之前 Public WDestination as Workbook Sub Publ

尝试通过复制此链接中的代码来执行此多级排序。我只在这里粘贴了相关代码

我犯了一个错误

对象变量未设置为on

有人知道为什么吗?

公共问题
  • 发生错误的原因可能是您没有声明sht 变数
  • 必须在循环中包含过滤器,否则它将循环 浏览工作表并仅对最后找到的应用过滤器 工作表
  • 不能在过程内部将变量声明为Public, 您必须使用Dim(或Static)
代码 如果要将变量声明为Public,则它必须位于模块中所有过程之前

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

您在何处设置目标?由于隐私原因,我没有显示目标。在没有排序的情况下,宏运行正常,所以我假设这不是问题。我粘贴的代码是为了说明,所以公共变量设置在正确的位置,所以我假设问题是必须将筛选器包括在循环中,否则它将在工作表中循环,并仅将筛选器应用于最后找到的工作表
With DestinationShVar.Sort
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
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