Private Sub Worksheet_Change(ByVal Target As Range)
Dim rHdr As Range, rHdrs As Range
Dim strFirstAddr As String
If Target.Address <> "$A$1" Then Exit Sub 'this address is your validation address where you select the header
Set rHdr = Range("Headers").Find(Target.Value, LookIn:=xlFormulas) 'assumes your header range is named "Headers"
If Not rHdr Is Nothing Then
strFirstAddr = rHdr.Address
Set rHdrs = rHdr
Do
Set rHdrs = Application.Union(rHdrs, rHdr)
Set rHdr = Range("Headers").FindNext(rHdr)
Loop Until rHdr.Address = strFirstAddr
Range("Headers").EntireColumn.Hidden = True
rHdrs.EntireColumn.Hidden = False
End If
End Sub
Seems strange that the Data Validation is in A1 and so is one of the headers (Personnel) in column A. So if A1 is set to Logistics, column A would be hidden because its heading didn't match. However, that also means A1 is hidden which would make it hard to use the Data Validation again.Data validation cell (A1) Personnel, Logistics, Facilities
Column.............................A.................B...............C.................D................E...............F.............G...............Z
Column header (row 3).....Personnel......Personnel.....Logistics......Personnel......Logistics.....Facilities....Logistics.......etc.
Macro in words:
If cells in range A3:Z3 contain the value in cell A1 (e.g. "Personnel"), then show only those columns (e.g. A, B and D), and hide all other columns (in this range A:Z).
Private Sub Worksheet_Change(ByVal Target As Range)
Dim cel As Range, Headers As Range
Dim s As String
Set Headers = Range("B3:AA3")
If Target.Address = "$A$1" Then
s = Target.Value
Application.ScreenUpdating = False
If s = "" Then
Headers.EntireColumn.Hidden = False
Else
For Each cel In Headers
cel.EntireColumn.Hidden = Not cel.Value = s
Next cel
End If
Application.ScreenUpdating = True
End If
End Sub
The Worksheet_Change event is not triggered by a formula result changing. Since you have a formula in A1 on the DV sheet, that's the reason nothing is happening.Hi,
I have a similar problem and was able to use the above code. However, the macro only works if in A1 (data validation) I type the name of the department. I actually want to link this A1 to a Combobox that I created in another sheet (called Start info, reference cell D5). If I say that A1='Start info'$D$5, and select a different option in the Combobox, the macro doesn't recognize this as a change and the macro doesn't run. How do I need to amend the code?
My worksheet to which the macro should apply is called "DV". I name ranged B3:CF3 as Headers. The worksheet with the Combobox is "Start info" and has reference cell D5.
I hope you can help out, thanks!
Private Sub ComboBox1_Change()
Dim cel As Range, Hdrs As Range
Dim s As String
Set Hdrs = Sheets("DV").Range("Headers")
s = ComboBox1.Value
If s = "" Then
Hdrs.EntireColumn.Hidden = False
Else
For Each cel In Hdrs
cel.EntireColumn.Hidden = Not cel.Value = s
Next cel
End If
Hdrs.Parent.Activate
End Sub