【问题标题】:Excel VBA Sort, error 1004 on .ApplyExcel VBA 排序,.Apply 上的错误 1004
【发布时间】:2014-09-25 21:40:39
【问题描述】:

我在 VBA 中使用排序时遇到问题。我看到了这个答案对我不起作用的帖子:Sort in VBA

我相信您可以对最多 nr 个记录进行排序。那是对的吗?我想对具有 188,000 条记录的工作表/表格中的 4 个条件进行排序。
我总是在.Apply 语句中遇到错误:"run-time error '1004': application-defined or object-defined error"

在我的代码下面:

Sub Sort_Table()

    Dim sht As Worksheet

    Set sht = ActiveWorkbook.Worksheets("Sheet1")

    sht.Activate

    With sht.ListObjects("Table1").Sort

        .SortFields.Clear
        .SortFields.Add Key:=Range("Table1[Date]"), SortOn:=xlSortOnValues,    Order:=xlAscending ', DataOption:=xlSortNormal
        .SortFields.Add Key:=Range("Table1[Country Code]"), SortOn:=xlSortOnValues, Order:=xlAscending ', DataOption:=xlSortNormal
        .SortFields.Add Key:=Range("Table1[Rating]"), SortOn:=xlSortOnValues, Order:=xlAscending ', DataOption:=xlSortNormal
        .SortFields.Add Key:=Range("Table1[Segment]"), SortOn:=xlSortOnValues, Order:=xlAscending ', DataOption:=xlSortNormal
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply

    End With

End Sub 

【问题讨论】:

    标签: vba sorting excel


    【解决方案1】:

    潜在问题

    实际上也许您不应该在With 中使用Apply,因为您的对象在With 块结束后才真正更新。
    例如,当您使用Apply 时,您的参数(.SortFields 等...)尚未设置。我不是 100% 确定,因为我现在没有 EXCEL 可以测试,而且正如您所指出的,似乎不是每个人都对这段代码有这个问题,但这可能是一个原因。

    (潜在)解决方案

    尝试做:

    With sht.ListObjects("Table1").Sort
    
        .SortFields.Clear
        .SortFields.Add Key:=Range("Table1[Date]"), SortOn:=xlSortOnValues,    Order:=xlAscending ', DataOption:=xlSortNormal
        .SortFields.Add Key:=Range("Table1[Country Code]"), SortOn:=xlSortOnValues, Order:=xlAscending ', DataOption:=xlSortNormal
        .SortFields.Add Key:=Range("Table1[Rating]"), SortOn:=xlSortOnValues, Order:=xlAscending ', DataOption:=xlSortNormal
        .SortFields.Add Key:=Range("Table1[Segment]"), SortOn:=xlSortOnValues, Order:=xlAscending ', DataOption:=xlSortNormal
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
    
    End With
    
    sht.ListObjects("Table1").Sort.Apply
    

    如果这不能解决问题,请告诉我

    其他潜在问题/解决方案

    • 您处理的工作表(排序)受到保护
    • 看看这个问题:Excel VBA Sort

    无论如何希望它有所帮助......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多