Reputation: 124
I am not sure why my code is not working. It is intended to recognise when I press a button (saying "Hide1") and search through each column, row by row, looking for cells that have the value 1
Once it does this, it should change the button to say "Show 1". However, when I run it, simply nothing happens.
Here is the macro for Excel:
Sub Hide_columns()
Dim i As Integer
Dim j As Integer
i = 3
j = 4
Do Until i = 26
Do Until j = 54
With ActiveSheet.Cells(i, j)
If .Value = 1 Then
ActiveSheet.Columns(i).EntireColumn.Hidden = True
With ActiveSheet.Shapes(Application.Caller).TextFrame.Characters
If .Text = "Show 1" Then
.Text = "Hide 1"
ElseIf .Text = "Hide 1" Then
.Text = "Show 1"
Else
MsgBox ("VBA has gone wrong.")
Exit Sub
End If
End With
End If
End With
j = j + 1
Loop
i = i + 1
Loop
End Sub
Upvotes: 0
Views: 321
Reputation: 96753
You must re-structure the inner loop:
Sub Hide_columns()
Dim i As Integer
Dim j As Integer
i = 3
Do Until i = 26
j = 4
Do Until j = 54
With ActiveSheet.Cells(i, j)
If .Value = 1 Then
MsgBox i & vbCrLf & j
ActiveSheet.Columns(i).EntireColumn.Hidden = True
With ActiveSheet.Shapes(Application.Caller).TextFrame.Characters
If .Text = "Show 1" Then
.Text = "Hide 1"
ElseIf .Text = "Hide 1" Then
.Text = "Show 1"
Else
MsgBox ("VBA has gone wrong.")
Exit Sub
End If
End With
End If
End With
j = j + 1
Loop
i = i + 1
Loop
End Sub
Explanation: The first time through the outer loop (for Column A), the row number, j
, starts at 4 and loops until it's 54. But the second time through the outer loop (for Column B), j
is still stuck at 54, so no rows in Column B get checked. To fix this, reset j
to 4 each time you move to a new column, as shown above.
Upvotes: 1