Faster way to hide empty rows

2019-01-28 04:20发布

问题:

I am trying to hide all rows where the value of the cell in Column A is blank (i.e. empty). I was trying to use the following code:

Range("A7:A117").SpecialCells(xlCellTypeBlanks).EntireRow.Hidden = True

However, every cell in Column A has a VLOOKUP formula and the xlCellTypeBlanks considers a cell with a formula, but no value, not to be blank.

So I tried using the following code, but it is extremely slow.

For i = 17 To 117
  If ActiveSheet.Cells(i, 1) = "" Then
    ActiveSheet.Cells(i, 1).EntireRow.Hidden = True
End If

How do I speed it up?

回答1:

Why don't you try AutoFilter:

Range("A7:A117").AutoFilter 1, "<>", , , False


回答2:

It is not the for loop that is slow it is that you are updating the screen everytime something changes (this uses a fair bit of processing power and thus slows everything down). if you turn screen updating off before you hide the rows then turn it back on after it will only update once and the script will run much much faster. I tried it with 100 rows and it was almost instant.

Sub hideEmptyRows()

Application.ScreenUpdating = False

For i = 1 To 117
  If ActiveSheet.Cells(i, 1) = "" Then
    ActiveSheet.Cells(i, 1).EntireRow.Hidden = True
End If
Next i

Application.ScreenUpdating = True

End Sub


回答3:

Range("A7:A117").AutoFilter 1, "<>", , , False

It hides empty cells but if you try to unhide with mouse you cannot



回答4:

Here's an answer without Autofilter :

Dim totalRange As Range
ActiveSheet.Range("A17:A117").Hidde = false


For Each cell In ActiveSheet.Range("A17:A117")
   If cell = "" And totalRange Is Nothing Then
        Set totalRange = cell
   ElseIf cell = "" Then
        Set totalRange = Application.union(totalRange, cell)
   End If
Next

If Not totalRange Is Nothing Then
    totalRange.EntireRow.Hidden = True
End If