Automating financial reports or dashboard layouts with Visual Basic for Applications (VBA) frequently involves hiding or unhiding columns and rows dynamically via scripts. However, executing statements such as Columns("D:G").EntireColumn.Hidden = True or Rows(5).Hidden = False can trigger Run-time error ‘1004’: Unable to set the Hidden property of the Range class. This failure occurs due to worksheet protection, merged cells overlapping boundaries, or table structure locks.
Unprotect Worksheet Before Modifying Range Visibility
Protected worksheets prohibit macro-driven layout alterations unless protection is lifted or UserInterfaceOnly mode is active:
- In the VBA Editor (Alt + F11), locate the procedure throwing the runtime exception.
- Prepend the hiding command with an explicit unprotect call:
Sub ToggleVisibility() Dim ws As Worksheet Set ws = ThisWorkbook.Sheets("Report") ' Unprotect sheet ws.Unprotect Password:="YourPassword" ' Modify row or column visibility ws.Columns("C:F").EntireColumn.Hidden = True ' Re-protect sheet ws.Protect Password:="YourPassword", UserInterfaceOnly:=True End Sub - Utilising
UserInterfaceOnly:=Truepermits subsequent VBA code execution without requiring repeated manual unprotect calls.
Resolve Merged Cell Conflicts
Hiding a subset of columns that form part of a horizontally merged range spanning visible columns triggers error 1004:
- Inspect the target range for merged cells using Home > Find & Select > Go To Special > Blanks / Objects or visually check header rows.
- Select the merged cells, click Merge & Center on the ribbon to unmerge them, and use Format Cells > Alignment > Horizontal > Center Across Selection instead.
Ensure Filter Modes Do Not Conflict With ListObjects
When manipulating visibility inside structured Excel Tables (ListObjects), setting row visibility directly can clash with active AutoFilter states. Call ws.ShowAllData or clear table filters before assigning row hidden attributes.