Exl 范围排序错误



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

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。问题出在范围选择还是在工作表选择中?

第二种排序的问题是 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

最新更新