Excel VBA Sort, error 1004 on .Apply

时间秒杀一切 提交于 2020-03-06 00:58:52

问题


I'm having issues using sort in VBA. I saw this thread for which the answers don't work for me: Sort in VBA

I believe there is a maximum nr of records on which you can sort. Is that correct? I want to sort on 4 criteria in a sheet/table with 188,000 records.
I always get an error on the .Apply statement: "run-time error '1004': application-defined or object-defined error"

Below my code:

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 

回答1:


Potential problem

Actually maybe you shouldn't the Apply inside the With since your object is really updated after the end of the With block.
For instance here your parameters (.SortFields etc ...) are not yet set when you use Apply. I'm not 100% sure because I doesn't have EXCEL to test right now, and it seem not everyone have this problem with this code as you pointed out, but that may be a reason.

(potential) Solution

Try doing:

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

Tell me if this doesn't solve the issue

Other potential problems/solutions

  • The sheet you work on (Sorting) is protected
  • Check out this question: Excel VBA Sort

Hope it helped anyway ...



来源:https://stackoverflow.com/questions/26037735/excel-vba-sort-error-1004-on-apply

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!