1

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

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

我已经搜索并查看了许多示例,尝试了许多设置Range参考的变体,但没有任何效果。

请问什么是正确的参考语法?

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

4

1 回答 1

4

好吧,您没有destLastRow在此行中输入行号
With wsCrewDetail.Range(Cells(4, 1), Cells(destLastRow, destLastCol))

另外,不要使用Integer变量,使用Long. 它们效率更高,也可以满足大量需求。

建议

  • 使用较短的变量(例如wsWorksheet)可以更轻松地键入和阅读代码
  • 使用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
于 2013-01-13T02:25:13.083 回答