VBA: Referencing a named range

Guraknugen

New Member
Joined
Mar 15, 2017
Messages
35
Let's say I have a named range like this:
Name: "MyRange"
Range address: "A2:C101"
Sheet name: "MySheet"

This is the only way so far that I could reference that name:
VBA Code:
    Dim oRange As Range
    Set oRange = Worksheets("MySheet").Range("MyRange")

So it works, but since Excel already knows that "MyRange" is actually "MySheet!A2:C101", Worksheets("MySheet") seems a little bit redundant.
I suppose there's a better way, but so far the few things I tried has failed, such as:

VBA Code:
Set oRange = Range("MyRange") ' Yields a runtime error no. 1004.
Set oRange = ThisWorkbook.Names("MyRange").RefersToRange ' 1004 again.



For reference, this is very easy in LibreOffice Calc:
vba]oRange = ThisComponent.NamedRanges.getByName("MyRange").getReferredCells()
No need to tell it what sheet it's on, it's already in the range name definition, just like in Excel.
 

Excel Facts

Back into an answer in Excel
Use Data, What-If Analysis, Goal Seek to find the correct input cell value to reach a desired result
maybe

VBA Code:
Set oRange = [MyRange]

or just use [MyRange] where you are using oRange
 
Upvote 0
This should work but it's risky. If you have the same name set at both a workbook variable and a worksheet variable, you will get a different result depending on which sheet is active.
The name scoped to the activesheet will take precedence over the workbook name.
VBA Code:
    Set oRange = Range(ActiveWorkbook.Names("MyRange").RefersTo)

Note: If you make your range a Table then the name can only be used once and is scoped to the workbook, so Range("MyTableName") or Range("MyTableName").ListObject works
 
Upvote 0

Forum statistics

Threads
1,215,526
Messages
6,125,329
Members
449,218
Latest member
Excel Master

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