1

1st i explain what i'm trying to do. I have a workbook with many sheets and each of them have many named ranges. I want to loop through named ranges on a specific sheet and then hide/unhide them, if it has a specific name. At start i want to isolate the sheet and there i have the problem. I'm trying to get the name of the sheet, the range is on and assign that name to a variable. Here is the part of the code, i'm having problems with:

Dim rng as Name
Dim shP as String
for each rng in ThisWorkbook.Names
shp = rng.RefersToRange.Parent.Name 'here i get the error
... rest of the code ...

If i just Debug.Print rng.RefersToRange.Parent.Name instead in that line, i get the sheet name printed out in immediate window. I also tried to Dim shP as Variant but it didn't helped.

Thank you in advance for your answers.

2 Answers 2

2

You probably have a Name in the workbook that does not correspond to a block of cells. Here I assign the Name when to the formula =now()

enter image description here

If I run:

Sub WhatsInaName()
    Dim nm As Name, s As String

    For Each nm In ThisWorkbook.Names
        MsgBox nm.RefersToRange.Parent.Name
    Next nm

End Sub

I also get a 1004

You should first run:

Sub listum()

    With ActiveWorkbook
        If .Names.Count > 0 Then
            For i = 1 To .Names.Count
                MsgBox (i & "  " & .Names(i).Name)
            Next
        End If
    End With
End Sub

to verify each Name is a cell block.

Sign up to request clarification or add additional context in comments.

3 Comments

Yes, you identified the problem correctly. One range lost it's cell block. Is there a way to check and skip those faulty ranges? I don't quite understand the point of your last code block.
@Ale I would temporarily use some OnError logic to skip the "bad" Names ...........................in the long run you should remove them!
Ok, thx. In the long run all ranges will be proper. Just now, while i work on that file some of them may break. I think, i got my answer now.
0

If you are getting a worksheet, then you need to use a Worksheet object.

Option Explicit
Sub Test()

    Dim rng As Name
    Dim shP As Worksheet
    For Each rng In ThisWorkbook.Names
        Set shP = rng.RefersToRange.Parent 'here i get the error
    '... rest of the code ...
    Next rng

End Sub

Then you can use the shP as if it were a worksheet.

2 Comments

If i do that, i get the same error. I just want to get the name of the sheet, so i can compare it later on.
This worked for me with no errors, to get the name you just need to use shP.Name whenever needed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.