VBA Hide/Unhide Columns Based On Value

bobslow21

New Member
Joined
Jan 18, 2012
Messages
9
I am trying to write a macro to hide/unhide a column based on the value in Row 1 of that column. The range needs to look over several hundred cells.

Example if A1 = 0 then hide Column A
If A1, B1, R1 = 0 the Hide Columns A, B, R etc..
 

Excel Facts

Lock one reference in a formula
Need 1 part of a formula to always point to the same range? use $ signs: $V$2:$Z$99 will always point to V2:Z99, even after copying
This will hide all columns where there is a value of 0 in the first row:
Code:
Sub Macro1()
 
Dim i As Long
 
Application.ScreenUpdating = False
 
For i = Cells(1, Columns.Count).End(xlToLeft).Column To 1 Step -1
    If Cells(1, i) = 0 Then Cells(1, i).EntireColumn.Hidden = True
Next i
 
Application.ScreenUpdating = True
 
End Sub
 
Last edited:
Upvote 0
This will hide all columns where there is a value of 0 in the first row:
Code:
Sub Macro1()
 
Dim i As Long
 
Application.ScreenUpdating = False
 
For i = Cells(1, Columns.Count).End(xlToLeft).Column To 1 Step -1
    If Cells(1, i) = 0 Then Cells(1, i).EntireColumn.Hidden = True
Next i
 
Application.ScreenUpdating = True
 
End Sub


Perfect, except how do I have it unhide when its not zero. Will be assigning the macro to a button so every time I hit the button it hides all 0 and unhides everything else??
 
Upvote 0
Perfect, except how do I have it unhide when its not zero. Will be assigning the macro to a button so every time I hit the button it hides all 0 and unhides everything else??
You could unhide all the hidden columns before running your loop so that it will just hide or re-hide your zeroes...

Columns.Hidden = False
 
Upvote 0

Forum statistics

Threads
1,223,785
Messages
6,174,539
Members
452,571
Latest member
MarExcelTips

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