Hide column based on cell value

olympiac

Board Regular
Joined
Sep 26, 2010
Messages
158
I am using the code below to hide a column based on a cell value.
I need to repeat this macro from column C to column AF.
How do I need to modify it to avoid copying this code for each colum?

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Range("C5").Value = 0 Then
Columns("C").EntireColumn.Hidden = True
Else
Columns("C").EntireColumn.Hidden = False
End If
End Sub


Thanks
 
I used the below to macro to do what I needed, but need this to run every time Cells C3, C4, and C5 change.

Sub HideColumns()
Columns("G:FA").Select
Selection.EntireColumn.Hidden = False
Application.ScreenUpdating = False
For Each cll In Range("E1:FA1")
If (cll.Value = 0) And (cll.Value <> "") Then cll.EntireColumn.Hidden = True
Next cll
Application.ScreenUpdating = True
Range("C4").Select
End Sub
A couple of questions...

1) Your loop can hide Columns E and F (second red highlighted text) in addition to Columns G:FA, however you only unhide Columns G:FA (first red highlighted text) at the beginning of your code... does that mean Column E and F will never be shown again once it becomes hidden, of was that "G" supposed to have been "E"?

2) Are you selecting cell C4 at the end because you need that specific cell selected or are you selecting it in order to unselect the columns you selected at the beginning of your code?
 
Upvote 0

Excel Facts

Formula for Yesterday
Name Manager, New Name. Yesterday =TODAY()-1. OK. Then, use =YESTERDAY in any cell. Tomorrow could be =TODAY()+1.

Forum statistics

Threads
1,225,155
Messages
6,183,212
Members
453,151
Latest member
Lizamaison

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