Excel VBAsorting不工作对于worksheet.range引用是正确的语法

用下面的代码,我得到一个错误:

Run-time error '1004' Method 'Range' of object'_Worksheet failed.

  Dim destLastCol As Integer 'last column in range Dim destLastRow As Integer 'last row in range Dim wsCrewDetail As Worksheet ' Set wsCrewDetail = Worksheets("CrewDetail_M") destLastCol = integer assigned previously destLastRow = integer assigned previously With wsCrewDetail.Range(Cells(4, 1), Cells(destLastRow, destLastCol)) <== error here .Sort Key1:=.Cells(4, 2), Order1:=xlAscending, _ key2:=.Cells(4, 1), Order2:=xlAscending, _ key3:=.Cells(4, 3), order3:=xlAscending, Header:=xlYes End With 

我已经search和查看了许多例子,试图设置Range参考许多变化,没有任何工作。

什么是正确的参考语法?

编辑添加destLastRow =先前分配的整数,并编辑以显示destLastCol

那么你不是在这一行中提供一个行号到destLastRow
With wsCrewDetail.Range(Cells(4, 1), Cells(destLastRow, destLastCol))

另外,不要使用Integervariables,使用Long 。 他们更有效率,也迎合大量。

build议

  • 使用较短的variables(如ws for Worksheet)可以更轻松地键入和读取代码
  • 使用Long而不是Integer
  • 我通常会设置一个工作范围( rng1 ),而不是使用从工作表开始的较长对象
  • 虚拟destLastRowdestLastCol

示例代码

  Dim destLastCol As Long 'last column in range Dim destLastRow As Long 'last row in range Dim ws As Worksheet Dim rng1 As Range Set ws = Worksheets("CrewDetail_M") destLastCol = 6 destLastRow = 10 Set rng1 = ws.Range(ws.Cells(4, 1), ws.Cells(destLastRow, destLastCol)) With rng1 .Sort Key1:=.Cells(4, 2), Order1:=xlAscending, _ key2:=.Cells(4, 1), Order2:=xlAscending, _ key3:=.Cells(4, 3), order3:=xlAscending, Header:=xlYes End With