0

I have a code that finds the last row of data in column E and selects the column to that last row. I want to be able to select associated data in columns B through D that goes with column E and then sort based on column B. So I thought I would just find the last row in column E then resize by 3 columns and sort from that selection but I keep getting a run-time error 1004 application-defined or object-defined error. I have provided the code I'm using below. Columns B through D contain data past the end of column E. Thanks!

ws.Range("E1:E" & finalrow).Resize(0, 3).Select
Community
  • 1
  • 1
Brianna Cates
  • 337
  • 1
  • 7
  • 22

2 Answers2

1

You may not always be starting in the first row (e.g. E1) so lastRow may not be applicable without some maths. In that case, use With ... End With statements to shorten the code while explicitly referencing the correct cell and cell ranges.

dim lastRow as long
with ws
    lastRow = .cells(.rows.count, "E").end(xlup).row
    'option 1
    .range("B5:D" & lastRow).select

    'option 2
    with .range("E5:E" & lastRow)
        .offset(0, -3).resize(.rows.count, 3).select
    end with

    'option 3
    .range("E5", .cells(lastRow, "G")).offset(0, -3).select
end with

See How to avoid using Select in Excel VBA macros for more methods on getting away from relying on Range.Select and Range.Activate to accomplish your goals.

Community
  • 1
  • 1
0

Something like:

Sub SelectLast3Cols()

Dim ws As Worksheet, lrow As Long

Set ws = Sheets("Sheet3")
lrow = ws.Range("E" & ws.Rows.Count).End(xlUp).Row

    ws.Range("B1", ws.Range("D" & lrow)).Select

End Sub
Harley B
  • 543
  • 5
  • 14