Excel VBA不能隐藏行

我有这个代码,通过行,并检查重复。 如果有重复,应该隐藏该行。 但是为什么它不能隐藏它。

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 

我也尝试过Sheets("Sheet name").Rows("5:5").EntireRow.Hidden=True但是也没有效果。

尝试改变

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

至:

 Rows(aRow).Hidden = True 

注意 :正如@Rik Sportel所提到的,没有理由将它作为一个Function因为你没有返回任何值或对象,所以它可以是一个常规的Sub

要确保您的所有CellsRows完全符合Worksheet对象,请添加With语句:

 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