简体   繁体   中英

Excel VBA Sort, error 1004 on .Apply

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 

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 ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM