Toggle code to hide and unhide columns based on text in a row

newbie4321

New Member
Joined
Jun 20, 2024
Messages
1
Office Version
  1. 365
Platform
  1. Windows
Hi,
I have a spreadsheet with 2 columns for multiple dates - "revenue" and "gross profit". I want to create a toggle button to hide and unhide all columns with "revenue" text in row 4 and then another toggle button to hide and unhide all columns with "gross profit" in row 4. I can't quite crack the code on this to link it back to the text in row 4. Is someone able to assist please?
 

Attachments

  • Screenshot 2024-06-21 091413.png
    Screenshot 2024-06-21 091413.png
    3.7 KB · Views: 20

Excel Facts

Format cells as date
Select range and press Ctrl+Shift+3 to format cells as date. (Shift 3 is the # sign which sort of looks like a small calendar).
Try:
VBA Code:
Sub ToggleRevenueColumns()
    Dim ws As Worksheet
    Dim lastCol As Long
    Dim col As Long
    Dim cell As Range
   
    Set ws = ActiveSheet
    lastCol = ws.Cells(4, ws.Columns.Count).End(xlToLeft).Column
    Application.ScreenUpdating = False
   
    For col = 1 To lastCol
        If ws.Cells(4, col).Value = "Revenue" Then
            ws.Columns(col).Hidden = Not ws.Columns(col).Hidden
        End If
    Next col
   
    Application.ScreenUpdating = True
End Sub

VBA Code:
Sub ToggleGrossProfitColumns()
    Dim ws As Worksheet
    Dim lastCol As Long
    Dim col As Long
    Dim cell As Range
   
    Set ws = ActiveSheet
    lastCol = ws.Cells(4, ws.Columns.Count).End(xlToLeft).Column
    Application.ScreenUpdating = False
   
    For col = 1 To lastCol
        If ws.Cells(4, col).Value = "Gross" Then
            ws.Columns(col).Hidden = Not ws.Columns(col).Hidden
        End If
    Next col
   
    Application.ScreenUpdating = True
End Sub
 
Upvote 0

Forum statistics

Threads
1,223,713
Messages
6,174,043
Members
452,542
Latest member
Bricklin

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top