简体   繁体   中英

run time error 1004 unable to set the hidden property of the range class

I get the run time error when I open the workbook. The open function works great without the close function, but as soon as I add the close function I get the error. Any suggestions?

Private Sub Workbook_Open()

Application.ScreenUpdating = False
For Each cell In Range("A1:Z1")
If cell.Value = "X" Then
cell.EntireColumn.Hidden = True
Else
cell.EntireColumn.Hidden = False
End If
Next cell

End Sub

Private Sub Workbook_BeforeClose(Cancel As Boolean)

Dim ws As Worksheet

For Each ws In ThisWorkbook.Worksheets
ws.Protect "1962"
Next ws

ThisWorkbook.Protect "1962", True

ThisWorkbook.Save


End Sub

The error occurs because you protect the worksheet in the BeforeClose routine. Hence the Workbook_Open doesn't have access to update it the next time it is being opened. Try this:

Private Sub Workbook_Open()

    Dim cell As Range

    Application.ScreenUpdating = False
    ActiveSheet.Unprotect "1962"            '<<<<
    For Each cell In Range("A1:Z1")
    If cell.Value = "X" Then
        cell.EntireColumn.Hidden = True
    Else
        cell.EntireColumn.Hidden = False
    End If
    Next cell
    ActiveSheet.Protect "1962"              '<<<<

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM