Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excel - Run-time error '1004': Unable to set the hidden property of the range class

Tags:

excel

vba

I am new to scripting and I am trying to improve a existing Macro. I recorded a macro to remove duplicate and added it in a Main function which calls some other functions, but I am getting this error when I add the macro I recorded:

Run-time error '1004': Unable to set the hidden property of the range class

The code looks like

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim changed As Range
    Set changed = Intersect(Target, Range("J15"))
    If Not changed Is Nothing Then
        Range("A48:A136").EntireRow.Hidden = True
        Select Case Target.Value
            Case "Agriculture"
                Range("A48:A96").EntireRow.Hidden = False
            Case "Commercial"
                Range("A97:A136").EntireRow.Hidden = False
            Case "MDP"
                Range("A48:A61").EntireRow.Hidden = False
        End Select
        Range("J15").Select
    End If
End Sub
like image 765
user1917946 Avatar asked Dec 20 '12 07:12

user1917946


People also ask

What is run time error 1004 in VBA?

This error occurs when you try to open the file which does not exist in the mentioned path. For example, it could move, be renamed, or deleted from the mentioned path. One reason for this is the wrong type of path or file name with the excel extension.


2 Answers

Some possible answers:

  • You have a comment in one of the selected cells
  • You have some drawn objects which don't resize with text
  • Your worksheet is protected

When you set a breakpoint on the first line of the event handler, and then press F8 to step through the macro, I'm assuming it crashes on the line:

Range("A48:A136").EntireRow.Hidden = True
like image 191
Andy Brown Avatar answered Sep 19 '22 09:09

Andy Brown


This breaks things

When people say "You have a comment in one of the selected cells", keep in mind that THE COMMENT CAN BE IN A DIFFERENT COLUMN.

If a comment box is over the column you're trying to hide (like if you're hiding every column to the right and you have comments in a completely different column), this is the error you'll get.

If you try to manually hide the column, you'll get a different confusing error which is something along the lines of "hiding this column will push an object off of the sheet."

The comment box a few columns over is the object.

^ This would have saved me about 40 minutes of debugging.

like image 22
user1274820 Avatar answered Sep 17 '22 09:09

user1274820