0

I have this code that goes through rows and checks for duplicates. If there is a duplicate if should hide the row. But somewhy it doesn't hide it.

Function sumAll()

Dim firstRow As Long
firstRow = 5
Dim lastRow As Long
lastRow = 1424
Dim aRow As Long

Dim totalDoubles As Long
totalDoubles = 0

Dim sumResult As Double
sumResult = 0
Dim previousValue As String

previousValue = -1
For aRow = firstRow To lastRow
    If Cells(aRow, 1).Value <> previousValue Then
        sumResult = sumResult + Cells(aRow, 2)
        previousValue = Cells(aRow, 1)
        Cells(aRow, 1).EntireRow.Hidden = True
    Else
        totalDoubles = totalDoubles + 1

    End If
Next aRow
sumAll = sumResult
MsgBox ("end: " & totalDoubles)

End Function

I also tried Sheets("Sheet name").Rows("5:5").EntireRow.Hidden=True but it gave no effect as well.

1
  • 2
    Declare the whole thing as Sub sumAll() ... End Sub. A function is a thing that takes parameters and returns a return value. What you're doing needs a sub. During a function execution you can not alter the worksheets / workbook. Commented Jul 11, 2017 at 10:55

1 Answer 1

1

Try changing

Cells(aRow, 1).EntireRow.Hidden = True

to:

Rows(aRow).Hidden = True

Note: as @Rik Sportel mentioned, there's no reason for this to be a Function as you are not returning any values or objects from it, so it can be a regular Sub.

To make sure all your Cells and Rows are fully qualified with your Worksheet object, add the With statement:

With Sheets("YourSheetName")
    For aRow = firstRow To lastRow
        If .Cells(aRow, 1).Value <> previousValue Then
            sumResult = sumResult + .Cells(aRow, 2)
            previousValue = .Cells(aRow, 1)
            .Rows(aRow).Hidden = True
        Else
            totalDoubles = totalDoubles + 1
        End If
    Next aRow
End With
Sign up to request clarification or add additional context in comments.

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.