When sheet isn't selected I get an error when I try to use ranges

craig.penny

Well-known Member
Joined
May 8, 2009
Messages
656
I'm trying to make my code run faster by avoiding selecting anything. It works to a point but then I keep running into a problem when I try to access a range on a sheet that wasn't selected. I wrote a short example to understand the problem better.

Code:
Sub error1004()
 
Dim rng As Range
Dim shtName As String
 
shtName = "SheetName"
Set rng = Sheets(shtName).Range(Cells(2, 2), Cells(3, 3)) 'error 1004
rng.Copy
 
End Sub

I put this code in the "ThisWorkbook" and it works fine if sheet "SheetName" is selected but if a different sheet is selected it gives me error #1004. I feel like this is something really obvious that I'm just overlooking. Any help is greatly appreciated. Thanks.
 
Last edited:

Excel Facts

Links? Where??
If Excel says you have links but you can't find them, go to Formulas, Name Manager. Look for old links to dead workbooks & delete.
You need to qualify the Cells properties as well as the Range property with the worksheet object:
Code:
Sub error1004()
 
Dim rng As Range
Dim shtName As String
 
shtName = "SheetName"
Set rng = Sheets(shtName).Range(Sheets(shtName).Cells(2, 2), Sheets(shtName).Cells(3, 3)) 'error 1004
rng.Copy
 
End Sub

or you can neaten that up with a With...End With statement
Code:
Sub error1004()
 
Dim rng As Range
Dim shtName As String
 
shtName = "SheetName"
with Sheets(shtName)
   Set rng = .Range(.Cells(2, 2), .Cells(3, 3))
end with
rng.Copy
 
End Sub
 
Upvote 0

Forum statistics

Threads
1,215,544
Messages
6,125,438
Members
449,225
Latest member
mparcado

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top