简体   繁体   English

Excel VBA排序错误1004

[英]excel vba sort error 1004

i'm using this code for sorting (checked for Excel 2010/2013): 我正在使用以下代码进行排序(已检查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. 我遍历具有不同值的工作表70次,然后将其排序并导出为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. 一切正常,但大约30次后出现错误1004。如果我再次在30点开始循环,则工作正常。 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? excel内部是否有缓冲区,我必须不时清除该缓冲区?

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. 而且,只需不使用Activate ,也不要使用Select更糟糕的Select ,因此将Sheets().ActivateActiveSheet.SortSheets().Sort ,您的代码将更加高效。

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. '这有效,但不对降序的数据进行排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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