Excel vba - 范围排序错误

问题描述 投票:1回答:1

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

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 vba excel-vba
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.