Home » excel » excel – Listing named ranges resulting in error #REF

excel – Listing named ranges resulting in error #REF

Posted by: admin May 14, 2020 Leave a comment

Questions:

enter image description here

These are 4 ranges (demo ranges). As you can see, the selected range is named as numbers2. Similarly, a5:a9 is numbers1, b2:b3 is alphabets1 and d2:d3 is alphabets2. I am displaying the named ranges in another sheet in same workbook.
Here’s the code :

Sub namedRanges()
Dim nm As Name, n As Long, y As Range, z As Worksheet
Application.ScreenUpdating = False

Dim sheet_name As String: sheet_name = InputBox("Provide the name of the worksheet where to list all the named ranges")
Sheets.Add After:=Sheets(Sheets.Count)
Sheets(ActiveSheet.Name).Name = sheet_name

Set z = ActiveSheet
n = 2
With z
    .[a1:xfd104856].ClearContents
    .[a1:b1] = [{"Name","Refers to"}]
    For Each nm In ActiveWorkbook.Names
        .Cells(n, 1).End(xlUp)(2) = nm.Name
        .Cells(n, 2).End(xlUp)(2) = "'" & nm.RefersTo
        n = n + 1
    Next nm
End With
Application.ScreenUpdating = True
End Sub

Everything is working fine, except I am getting some extra named ranges which aren’t there in the worksheet.

enter image description here

See, the new worksheet which is created. and there are two columns created. But I should get 4 named ranges, instead I am getting more.

Any thing which is wrong in the code ?

How to&Answers:

Ribbon > Formulas > Names Manager:

enter image description here

You would see anything, which is declared in the workbook and how it is declared. In your code you are looping through ActiveWorkbook.Names and in your screenshot you are showing only the names in the current worksheet.