Hiding columns using VBA

Copper Contributor

I have a spreadsheet where the balance sheet and income summaries for each month of 2017 and 2018 are presented.  To clarify, January 2017 is next to January 2018, February 2017 is next to February 2018, etc.

I'm trying to write a Macro in VBA that hides all of the 2017 columns or the 2018 columns depending upon the year selected from a drop down box.  So far, I can hide 2017, but then if I pick 2018, everything is hidden.  I need for the routine to hide one year and not hide the other.

 

Here's what I have done so far:

Sub Hidecolumnsbasedoncellvalue()
Dim p As Range
        For Each p In Range("D4:AP4").Cells
            If p.Value = Range("C2").Cells Then
            p.EntireColumn.Hidden = True
        End If
                  
    Next p
        
End Sub
 
Any ideas of how to fix it?

 

6 Replies

before hiding 2018 - unhide 2017 first. and vice-versa
wouldn't that work?

pls see attached sample.

hope you can work something out of it.

thanks..

 

Just add this line before for-loop

Columns("D:AP").EntireColumn.Hidden = False

 

It works!  Much more sophisticated than mine and I don't understand it all yet, but thank you very much!

Very simple fix and it works! Thank you very much!
glad to hear it helped!