Exl vba - 范围排序错误

时间:2018-01-03 10:21:59

标签: excel vba excel-vba

我的代码中有两个范围排序部分:

With ws1 

  finalrow1 = .Cells(.Rows.Count, "A").End(xlUp).Row

   With .Range(.Cells(6, 1), .Cells(finalrow1, 9))
    .Sort Key1:=.Cells(6, 8), Order1:=xlDescending, _
          Key2:=.Cells(6, 6), order2:=xlDescending, _
          Key3:=.Cells(6, 2), order3:=xlDescending, Header:=xlGuess
   End With

End With

With ws4

finalrow4 = .Cells(.Rows.Count, "A").End(xlUp).Row

   With .Range(.Cells(6, 1), .Cells(finalrow4, 8))
   .Sort Key1:=.Cells(6, 8), Order1:=xlDescending, _
         Key2:=.Cells(6, 6), order2:=xlDescending, _
         Key3:=.Cells(6, 4), order3:=xlDescending, _
         Key4:=.Cells(6, 2), order4:=xlDescending, Header:=xlGuess
   End With

End With

ws1ws4的位置:

Set ws1 = ThisWorkbook.Sheets("Sheet1")
Set ws4 = ThisWorkbook.Sheets("Sheet4")

在第二次“排序”中,我得到Application-defined or object-defined error。这只是代码的一部分。 我还有另一个excel文件中的ws2ws3。 范围选择或工作表选择中存在问题吗?

1 个答案:

答案 0 :(得分:1)

第二种排序的问题是excel允许max three columns通过VBA同时排序。

如果您手动对多个列HFDB进行排序,则excel会在内部以相反顺序对它们进行排序以完成排序,即它对序列BDFH中的列。

因此,您可以使用此概念通过VBA对多于三列进行排序。您只需要在最后一列上单独应用排序,然后照常对其余三列应用排序。

请试一试......

With ws4
    finalrow4 = .Cells(.Rows.Count, "A").End(xlUp).Row
    With .Range(.Cells(6, 1), .Cells(finalrow4, 8))
     .Sort Key1:=.Cells(6, 2), order1:=xlDescending, Header:=xlGuess
     .Sort Key1:=.Cells(6, 8), order1:=xlDescending, _
           Key2:=.Cells(6, 6), order2:=xlDescending, _
           Key3:=.Cells(6, 4), order3:=xlDescending, Header:=xlGuess
    End With
End With
相关问题