Changed name range according to variable

pablus

New Member
Joined
Aug 28, 2018
Messages
1
[TABLE="width: 500, align: center"]
<tbody>[TR]
[TD]List No.
[/TD]
[TD]Name
[/TD]
[/TR]
[TR]
[TD]1
[/TD]
[TD]Pablo
[/TD]
[/TR]
[TR]
[TD]2
[/TD]
[TD]Pepe
[/TD]
[/TR]
[TR]
[TD]3
[/TD]
[TD]Luis
[/TD]
[/TR]
[TR]
[TD]4
[/TD]
[TD]Juan
[/TD]
[/TR]
[TR]
[TD]5
[/TD]
[TD]Manuel
[/TD]
[/TR]
</tbody>[/TABLE]

Hello everyone!

Let's say I have an small array as shown in the table and I want to create a named range for each column with all its elements. When I use the "Record Macro" tool it turn out this:

Sub Macro1()
'
' Macro1 Macro
'

'
Range("A2").Select
Range(Selection, Selection.End(xlDown)).Select
ActiveWorkbook.Names.Add Name:="list_no", RefersToR1C1:= _
"=Sheet1!R2C1:R6C1"
Range("B2:B21").Select
ActiveWorkbook.Names.Add Name:="names", RefersToR1C1:="=Sheet1!R2C2:R6C2"
End Sub

What if the size of the array changes? Can I use a variable X, something like RefersToR1C1:="=Sheet1!R2C2:RXCX" ?


Thank you all very much for your help. :D
 

Excel Facts

Did you know Excel offers Filter by Selection?
Add the AutoFilter icon to the Quick Access Toolbar. Select a cell containing Apple, click AutoFilter, and you will get all rows with Apple
Try this. Also, the code is more readable if you use A1 notation instead of R1C1.
Code:
Public Sub Create_Named_Ranges()
    
    Dim lastRow As Long
    
    With Worksheets("Sheet1")
        lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
        ActiveWorkbook.Names.Add Name:="list_no", RefersTo:="='" & .Name & "'!$A$2:$A$" & lastRow
        ActiveWorkbook.Names.Add Name:="names", RefersTo:="='" & .Name & "'!$B$2:$B$" & lastRow
     End With
    
End Sub
 
Upvote 0

Forum statistics

Threads
1,223,893
Messages
6,175,240
Members
452,621
Latest member
Laura_PinksBTHFT

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