I usually use a macro to show and hide columns using a checkbox. I set it up by defining the columns in the macro code.
Sub Hideshow() If Range("A1").Value = "True" Then ActiveSheet.Columns("B:C").Hidden = False ElseIf Range("A1").Value = "False" Then ActiveSheet.Columns("B:C").Hidden = True Else Return End If End Sub
For this code, A1 = the result of the checkbox (True/False) and B:C are the columns I am hiding or, if already hidden; showing.
However, now I am making a more dynamic version of this, because I am getting bored of scrolling through the macro code and changing each column reference when a new column is added or the column range changes.
I have now put the columns I want to hide within cell A2 on my sheet e.g B:C
I would like the macro code to use the value of that cell as a 'defined range'? to show and hide the column range I have defined in cell A2.
I've found lots of similar posts, but they are slightly different and I can't make it work for my specific scenario.
The new one would look something like this
Sub Hideshow() If Range("A1").Value = "True" Then ActiveSheet.Columns(" The Value in A2 ").Hidden = False ElseIf Range("A1").Value = "False" Then ActiveSheet.Columns(" The Value in A2").Hidden = True Else Return End If End Sub
Any ideas?
This code should do the trick:
Sub HideShow()
Dim ColsToHide As String
ColsToHide = Sheet1.Range("A2") 'This will always get the value from the sheet with the codename Sheet1.
'Unhide if hidden, hide if not hidden.
ActiveSheet.Columns(ColsToHide).Hidden = Not ActiveSheet.Columns(ColsToHide).Hidden
End Sub
There are probably better ways to figure out which columns need hiding - is there anything specific about a column that decides if it should be hidden or not?