Error on Set Rng statement?

  • Thread starter Thread starter Steve
  • Start date Start date
S

Steve

Hi all. Any idea why this line errors out if the sheet Data is not
the active sheet? If I run the code while on the Data sheet, all
works well. If I run thwe code while on any other sheet, I get an
"application defined or object defined error". Thanks!

Set rng = Worksheets("Data").Range(Cells(1, 1), Cells(Rows.Count,
1).End(xlUp))
 
Sub routine()
Set rng = Worksheets("Data").Range(Cells(1, 1), Cells(Rows.Count,
1).End(xlUp))
MsgBox (rng.Address)
End Sub

will work if:

1. there is a worksheet named Data
2. column A in that sheet has some data in it.
 
When you have an unqualified range in a general module, it will refer to the
activesheet.

When you have an unqualified range in a worksheet module, it will refer to the
sheet holding the code.

so this will work

Set rng = Worksheets("Data").Range(Worksheets("Data").Cells(1, 1), _
Worksheets("Data").Cells(Rows.Count, 1).End(xlUp))

as will:

with Worksheets("Data")
Set rng = .Range(.Cells(1, 1), .Cells(Rows.Count, 1).End(xlUp))
End With

I'd use:

with Worksheets("Data")
Set rng = .Range("A1", .Cells(.Rows.Count, 1).End(xlUp))
End With
 
Awesome. Thanks guys!!

When you have an unqualified range in a general module, it will refer to the
activesheet.

When you have an unqualified range in a worksheet module, it will refer tothe
sheet holding the code.

so this will work

Set rng = Worksheets("Data").Range(Worksheets("Data").Cells(1, 1), _
              Worksheets("Data").Cells(Rows.Count, 1).End(xlUp))

as will:

with Worksheets("Data")
  Set rng = .Range(.Cells(1, 1), .Cells(Rows.Count, 1).End(xlUp))
End With

I'd use:

with Worksheets("Data")
  Set rng = .Range("A1", .Cells(.Rows.Count, 1).End(xlUp))
End With
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top