VBA: How to programmaticaly create named range pointing to programmatically created sheet?

StackOverflow https://stackoverflow.com/questions/22606486

  •  20-06-2023
  •  | 
  •  

Question

It seems this question also contains proper answer, Excel for some unfathomable reason won't execute it without error. So the question has changed a bit:

Why 1004?

Basically I want to use something like (This give me 1004):

Dim rngTmp As Range
For Each offer In SanitizedConstInfo("offers").keys()
    Set rngTmp = Sheets(offer).Range(Cells(1, 1), Cells(2, 2))
    ActiveWorkbook.Names.add name:=offer, RefersToR1C1:=rngTmp
    ActiveWorkbook.Names(offer).RefersToRange.Cells(1, 1) = offer
Next offer

offer is string containing some name (Yeah, I want to have both sheet and named range with same name - for now at least). Will have unknown number of those, so I just loop for each.

Q: How to add sheet information to RefersToR1C1, so that named range refers to certain sheet? (I know about 'Sheetname'!A1:A10 Syntax but want to do that with Sheet/Range/Cell objects if possible)

Was it helpful?

Solution

It's because you aren't fully qualifying your ranges, you need to be explicit:

With Sheets(offer)
    Set rngTmp = .Range(.Cells(1, 1), .Cells(2, 2))
End With

Dots before Cells are important.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top