简体   繁体   中英

1004 Application-Defined or Object Defined error

The error appears on the line before end sub, what is the correct way to select the range with the last row calculated?

Sub My_Script()
Dim LastRow As Long
    With ActiveSheet
        LastRow = .Cells(.Rows.Count, "D").End(xlUp).Row
    End With
  ActiveSheet.Range(Cells(LastRow, Columns("D:AH"))).Select
End Sub

The code below select all cells in the LastRow only , from Column "D" to Column "AH".

Sub My_Script()

Dim LastRow As Long

With ActiveSheet
    LastRow = .Cells(.Rows.Count, "D").End(xlUp).Row
    .Range(.Range("D" & LastRow), .Range("AH" & LastRow)).Select
End With

End Sub

If you wanted to select all rows (from row 1 to LastRow ), from Column "D" to Column "AH".

Sub My_Script()

Dim LastRow As Long

With ActiveSheet
    LastRow = .Cells(.Rows.Count, "D").End(xlUp).Row
    .Range(.Range("D1"), .Range("AH" & LastRow)).Select
End With

End Sub

Note : not sure why you want to Select this range ? You can set this Range to a variable of type Range , and later to Copy or whatever you want to do with it. There's hardly a reason to ever use Select .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM