I've got a worksheet with a range of cells (B15:BL15) with formulas in them returning either "Show" or "Hide". The values change when I make a selection from a form control (not ActiveX) combo box and I assigned the below macro to the combo box. The macro is supposed to show or hide the column based on the cell values.
The first time I make a selection all of the columns end up hidden regardless of the values in the cells. When I select it again, the code works fine (i.e. I select Option A and all columns in range are hidden. I choose Option B and then go back to Option A and the correct columns are now showing and hiding.). Anything I'm missing here?
Option Explicit
Sub ShowHide()
Cells.Columns.EntireColumn.Hidden = False ' Added to unhide all of the columns first.
Dim c As Range
For Each c In Range("B15:BL15").Cells ' Range of cells containing the formulas
With c
If .Value = "Hide" Then
.EntireColumn.Hidden = True
Else
.EntireColumn.Hidden = False
End If
End With
Next c
End Sub
Any help is greatly appreciatd!
Hope this helps someone!
The issue was being caused by the code running prior to all calculations finishing and updating the range. During the calc, the cells in the range briefly defaulted to "hide" which triggered the column to be hidden.
I found Application.CalculateUntilAsyncQueriesDone
which forced the code to run after all calculations finished and the range was updated. Revised code below:
Sub ShowHide()
Dim c As Long
Application.ScreenUpdating = False
Application.CalculateUntilAsyncQueriesDone
For c = 2 To 64
If Cells(16, c).Value = "Hide" Then
Columns(c).Hidden = True
Else
Columns(c).Hidden = False
End If
Next c
Application.ScreenUpdating = True
End Sub
Note: I saw multiple threads using and IF statement and then Application.CalculationState = xlDone
but that didn't work. If anyone knows why I'd love to understand.