I have a private sub that needs to create named ranges within another worksheet. It needs to stay a worksheet function, as it is a Worksheet_Change
sub. I have successfully been able to set a range variable equal to a range on another sheet with this line:
Set rng2 = Sheets("Lists").Range(Sheets("Lists").Cells(2, Col), Sheets("Lists").Cells(Unique, Col))
However, when I put rng2
into the other portion of my code, it simply refers to the correct range within the Active Sheet.
Here is what I have tried:
ActiveWorkbook.Names.Add Name:="Level" & Col, RefersTo:= _
"= " & Sheets("Lists").Range(Sheets("Lists").Cells(2, Col), Sheets("Lists").Cells(Unique, Col)).Address & ""
and:
ActiveWorkbook.Names.Add Name:="Level" & Col, RefersTo:= _
"=" & rng2.Address & ""
The bottom function works when it is within a module stored inside the workbook as a whole, but again, does not work within a worksheet sub.
I have also tried Sheets("Lists").rng2.Address
in the bottom attempt.
To reference a cell or range of cells in another worksheet in the same workbook, put the worksheet name followed by an exclamation mark (!) before the cell address. For example, to refer to cell A1 in Sheet2, you type Sheet2! A1.
To create a named range using VBA, you need to use the “Names” property further with the “Add” method. In add method, you have arguments to define the name that you wish to give to the range and specify the address of the range (make sure to use the dollar sign with the address to freeze the range).
To name a selected range, click the name box at the left end of the formula bar, type a name, and then press ENTER.
To copy a cell or a range of cells to another worksheet you need to use the VBA's “Copy” method. In this method, you need to define the range or the cell using the range object that you wish to copy and then define another worksheet along with the range where you want to paste it.
To have the address include the sheet's name, you have to set the external
parameter:
rng2.address(external:=True)
Your RefersTo
string needs to be something like "=Lists!A1"
. So all it's missing is the reference to the lists worksheet.
Try something like this:
Dim wsLists As Worksheet
Set wsLists = ThisWorkbook.Worksheets("Lists")
With wsLists
Set rng2 = .Range(.Cells(2, Col), .Cells(Unique, Col))
ThisWorkbook.Names.Add Name:="Level" & Col, RefersTo:="=" & rng2.Address(external:=True)
End With
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With