Reputation: 2315
With the code below I get an error:
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
I've searched and viewed many examples trying many variations on setting the Range
reference and nothing is working.
What is correct reference syntax please?
Edited to add destLastRow = integer assigned previously and edit to show destLastCol
Upvotes: 1
Views: 3699
Reputation: 55682
Well you aren't feeding a row number into destLastRow
in this line
With wsCrewDetail.Range(Cells(4, 1), Cells(destLastRow, destLastCol))
Plus, don't use Integer
variables, use Long
. They are more efficient and also cater for large numbers.
suggestions
ws
for Worksheet makes it easier to type and read codeLong
rather than Integer
rng1
) rather than use a longer object starting with the sheet destLastRow
and destLastCol
valuessample code
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
Upvotes: 4