简体   繁体   中英

excel vba sort error 1004

i'm using this code for sorting (checked for Excel 2010/2013):

    Worksheets("Tabelle4(1)").Activate
ActiveSheet.Sort.SortFields.Add Key:=Range( _
        "W2:W51"), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:= _
        xlSortNormal

I loop over a sheet 70 times with different values and sort and export them as a pdf. Everything works fine, but after approximately 30 times I get an error 1004. If I start the loop at this point 30 again it works fine. The problem doesn't seem to do with the values. Is there a buffer inside of excel, which I've to clear from time to time?

You should clear your Sort fields from time to time indeed, because they just accumulate and it'll be harder for you to prioritize them.

And just don't use Activate , nor Select which is even worse, so just combine Sheets().Activate and ActiveSheet.Sort to Sheets().Sort , your code will be much more efficient.

This should help you :

With Worksheets("Tabelle4(1)")
        .Sort.SortFields.Add _
            Key:=Range("W2:W51"), _
            SortOn:=xlSortOnValues, _
            Order:=xlDescending, _
            DataOption:=xlSortNormal

        .Sort.Orientation = xlTopToBottom
        .Sort.Apply
        'here is your export

        .Sort.SortFields.Clear
End With
    Set ws = Worksheets("Sheet1")
    Set rng = ws.Range(Cells(startRow, 1), Cells(endRow, 3))
        'startRow=2, endRow=18
        'Sort Table Date Decending Order
    ws.Sort.SortFields.Clear
    With ws
        .Sort.SortFields.Add Key:=rng, SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
        .Sort.Orientation = xlTopToBottom
        .Sort.SortMethod = xlPinYin
        .Sort.Apply
    End With

'This works but does not sort the data descending.

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