1

I created a simple spreadsheet with a bit of VBA code to hide/unhide based upon the color of the column header. If the column header is red, and I want it hidden, then I click the button "Hide". Alternatively, if I want those hidden columns to reappear, I click "Unhide". It works. Yay!

The actual task of unhiding/hiding works, the problem is that it takes entirely too long.

snip of project

Here's the code for hiding:

Sub HideColumnIfRed()
Dim c As Range
For Each c In Range("A:AT")

If c.Interior.Color = vbRed Then
c.EntireColumn.Hidden = True

End If

Next c

End Sub

Here's the code for unhiding:

Sub HideColumnIfRed()
Dim c As Range
For Each c In Range("A:AT")

If c.Interior.Color = vbRed Then
c.EntireColumn.Hidden = False

End If

Next c

End Sub

What can I do to optimize this task?

Thank you in advance.

Keegan
  • 21
  • 2

2 Answers2

1

As a quick (maybe dirty) fix you could intersect your columns you are after with the used range like that

For Each c In Intersect(Range("A:AT"), ActiveSheet.UsedRange)

But be careful as ActiveSheet might not always the sheet you expect it to be. On the other hand you already use Range("A:AT") without reference which already refers to ActiveSheet anyway.

Storax
  • 11,158
  • 3
  • 16
  • 33
1

I got it. I restricted the cells as suggested in @BigBen’s comment.

From this:

For Each c In Range("A:AT")

To this:

For Each c In Range("A2:AT2")

I then deleted the corresponding buttons, and recreated them. All works beautifully now.

Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
Keegan
  • 21
  • 2