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

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

  •  20-06-2023
  •  | 
  •  

문제

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)

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top