0

Im still a beginner when it comes to VBA and I'm trying to write a code that hides rows if its cell value equals zero and the user has chosen to set another cell value to the correct wording. However, the code I wrote doesn't seem to work; I'm sure I have forgotten to add something or am missing some key element but can't seem to figure out what it is.

I have posted my code below. Any help would be much appreciated.

Sub HideEmptyRows()

Application.EnableEvents = False

Worksheets("Filtered Data").Rows("7:600").EntireRow.Hidden = False

If Range("J7") = "Filter" Then

    For Each cell In Range("J10:J503")
        If cell.Value = 0 Then
            cell.EntireRow.Hidden = True
        End If
    Next cell

Application.EnableEvents = True

End Sub
Community
  • 1
  • 1
wildesbare
  • 7
  • 1
  • 4

2 Answers2

0

Consider:

Sub HideEmptyRows()
    Application.EnableEvents = False
    With Worksheets("Filtered Data")
        .Rows("7:600").EntireRow.Hidden = False

        If .Range("J7") = "Filter" Then
            For Each cell In .Range("J10:J503")
                If cell.Value = 0 Then
                    cell.EntireRow.Hidden = True
                End If
            Next cell
        End If

    End With
    Application.EnableEvents = True
End Sub

NOTE:

  1. used With
  2. small clean-up to the logic
Gary's Student
  • 95,722
  • 10
  • 59
  • 99
0
  1. You don't test to see whether there actually exists a worksheet named "Filtered Data".

  2. You unhide rows in Worksheets("Filtered Data") but then you check values and hide rows in whatever sheet happens to be the ActiveSheet.

  3. You did not declare the variable cell. Option Explicit is a good friend; use it.

  4. There is a missing End If.

Otherwise the code works; tested like this:

Option Explicit

Sub HideEmptyRows()

  Dim cell As Range

  Application.EnableEvents = False

  With Worksheets("Filtered Data")
    .Rows("7:600").EntireRow.Hidden = False
    If .Range("J7") = "Filter" Then
      For Each cell In .Range("J10:J503")
        If cell.Value = 0 Then
          cell.EntireRow.Hidden = True
        End If
      Next cell
    End If
  End With

  Application.EnableEvents = True

End Sub
AlexP
  • 4,370
  • 15
  • 15
  • What would I need to do to alter this code so every time that the "J7" input is changed the code automatically runs and there is no need for a button or a manual Run Sub. – wildesbare Jun 21 '18 at 15:20
  • See "[automatically execute an Excel macro on a cell change](https://stackoverflow.com/questions/409434)" on this site. – AlexP Jun 21 '18 at 15:42