0

I am trying to make two macros: one that hides rows based on a criterion in a certain column, and another that unhides rows based on the same criterion.

Here is the code for the first macro, which works fine:

Sub hide()
    Dim item As Variant

    For Each item In Range("f:f")
        If item = "complete" Then item.EntireRow.hidden = True
    Next
End Sub

It's the second macro, the unhiding one, that doesn't work for me. Excel tells me it cannot run the macro or all macros have been disabled. Here is the code for the second macro:

Sub Unhide()
    Dim item As Variant

    For Each item In Range("f:f")
        If item = "complete" Then
            item.EntireRow.hidden = False
    Next
End Sub

If it's relevant, each macro is located in its own module.

2

3 Answers 3

1

In your second macro you have a missing End If:

Sub Unhide()
    Dim item As Variant

    For Each item In Range("f:f")
        If item = "complete" Then
            item.EntireRow.hidden = False
        End If   ' <<<<<<<<<<<<< missing
    Next
End Sub

Add that, and you're good to go.

The difference between the first and the second Sub is this: in the first, you put the statement right after the Then. In the second, you go to a new line. Unlike in C, you need to indicate with an End If where the group of statements ends.

Normally you don't just get a "can't run code" error, but an actual Next without For type of error (that's what happened when I pasted your code and tried to compile it).

In future, click Debug->Compile VBA Project before trying to run your code, and heed the error messages. It can be quite a time saver.

Sign up to request clarification or add additional context in comments.

Comments

0

Why not just step through all the used rows in the spreadsheet and check the value of Column F?

Sub hide()
    Dim i As Integer
    For i = 1 to ActiveSheet.UsedRange.Rows.Count
        If ActiveSheet.Cells(i, 6).Value = "complete" Then
            ActiveSheet.Rows(i).EntireRow.hidden = True
        End If
    Next
End Sub

Further it would probably be cleaner to just combine the hide and unhide...

Sub hide(ByVal isHide As Boolean)
    Dim i As Integer
    For i = 1 to ActiveSheet.UsedRange.Rows.Count
        If ActiveSheet.Cells(i, 6).Value = "complete" Then
            ActiveSheet.Rows(i).EntireRow.hidden = isHide
        End If
    Next
End Sub

Comments

0

Just tested - The code is fine. You do need an End If in your Unhide procedure though, right before Next.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.