SOLVED

VBA Code to Unhide All Columns When User Clicks on a Worksheet

Copper Contributor

Hello Everyone,

I am a basic Excel user attempting my first VBA macro and being reminded that simple <> easy (at least not for me). 

Desired VBA outcome - When a user clicks on the "Data" worksheet tab, I want the macro to unhide any hidden columns, display columns A - CZ, and only display rows 1-18. I used ChatGPT to start. Countless iterations later, this ChatGPT code displays the rows correctly but does not unhide the hidden columns and show all columns. 

=========================ChatGPT=========================
Private Sub Worksheet_Activate()
Dim ws As Worksheet
Dim col As Range

' Set the worksheet object to the "Data" worksheet
Set ws = ThisWorkbook.Sheets("Data")

' Hide all rows and columns
ws.Rows.Hidden = True
ws.Columns.Hidden = True

' Set the range for rows 1 to 18 and columns A to CZ
Set rowRange = ws.Rows("1:18")
Set colRange = ws.Columns("A:CZ")

' Unhide rows and columns
rowRange.Hidden = False
colRange.Hidden = False
End Sub

=========================================================
Any suggestions to fix this are greatly appreciated!

Thom


2 Replies
best response confirmed by ThomT25 (Copper Contributor)
Solution

@ThomT25 

Try this version. And never rely on ChatGPT, please.

Private Sub Worksheet_Activate()
    Dim rowRange As Range
    Dim colRange As Range

    ' Hide all rows and columns
    Rows.Hidden = True
    Columns.Hidden = True

    ' Set the range for rows 1 to 18 and columns A to CZ
    Set rowRange = Rows("1:18")
    Set colRange = Columns("A:CZ")

    ' Unhide rows and columns
    rowRange.EntireRow.Hidden = False
    colRange.EntireColumn.Hidden = False
    Application.Goto Range("A1")
End Sub
Hello Hans,

THANK you SO much for solving my problem. I mistakenly inserted a module and pasted the code there, but it did not work. I then inserted the code into the worksheet object and it worked perfectly. - Thank you again and enjoy the rest of your week! - Thom
1 best response

Accepted Solutions
best response confirmed by ThomT25 (Copper Contributor)
Solution

@ThomT25 

Try this version. And never rely on ChatGPT, please.

Private Sub Worksheet_Activate()
    Dim rowRange As Range
    Dim colRange As Range

    ' Hide all rows and columns
    Rows.Hidden = True
    Columns.Hidden = True

    ' Set the range for rows 1 to 18 and columns A to CZ
    Set rowRange = Rows("1:18")
    Set colRange = Columns("A:CZ")

    ' Unhide rows and columns
    rowRange.EntireRow.Hidden = False
    colRange.EntireColumn.Hidden = False
    Application.Goto Range("A1")
End Sub

View solution in original post