gpt4 book ai didi

excel - 在我的代码中遇到问题进行多级排序

转载 作者:行者123 更新时间:2023-12-04 22:29:51 25 4
gpt4 key购买 nike

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

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

我收到一个错误

Object variable not set on


With DestinationShVar.Sort

有人会知道为什么吗?

最佳答案

公共(public)问题

  • 错误可能是因为您没有声明 sht
    多变的。
  • 您必须在循环中包含过滤器,否则它将循环
    通过工作表并将过滤器仅应用于最后找到的
    工作表。
  • 您不能将变量声明为 公众号 在程序内部,
    你必须使用 昏暗 (或静态)。

  • 编码
    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

    关于excel - 在我的代码中遇到问题进行多级排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54082516/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com