Home » excel » excel – VBA Runtime Error 1004 “Application-defined or Object-defined error” when trying to assign value to a variable

excel – VBA Runtime Error 1004 “Application-defined or Object-defined error” when trying to assign value to a variable

Posted by: admin May 14, 2020 Leave a comment

Questions:

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.

How to&Answers:

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.

Answer:

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.