简体   繁体   中英

Use cell's value as part of macro

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 eg 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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM