Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Macro Recording to define cell name

Tags:

excel

vba

I have recorded a macro with relative reference on, where the first cell is the name I want to give the range so I select the range I want to name -> right click -> define name -> since the name is already included in the first cell I don't need to change anything so -> I click OK.

Example
A1:B5 - I want to name it TSLA56
then I go to D1 to run the recorded macro to name D1:E5 to TSLA23

After the macro is done running it is still called D1

What am I doing wrong? Is this even possible?

Record Macro:

Sub DefineName()
'
' DefineName Macro
'

'
    ActiveCell.Range("A1:B5").Select
    ActiveWorkbook.Names.Add Name:="TSLA56", RefersToR1C1:="=Sheet1!R1C1:R5C2"
    ActiveWorkbook.Names("TSLA56").Comment = ""
End Sub

1: enter image description here

like image 584
J Singh Avatar asked Nov 28 '25 13:11

J Singh


1 Answers

While your actions are being recorded as relative wherever possible some things like the Name:= and .RefersTo:= when defining a name are not made relative. You can adjust this by editing and passing the selections address into the macro code line.

ActiveWorkbook.Names.Add Name:=selection.cells(1,1).value, refersTo:="=" & selection.address

selection.cells(1,1).value refers to the value in the top-left cell of any single or multiple cell selection.