Not sure how many Excel VBA gurus, besides myself ;-D, that hang around stackoverflow but here's an interesting question.
Goal: Efficiently show/hide rows based on the data in the row.
- Create a helper column that determines whether or not a row should be hidden.
- Have the formula in the helper column return an error or a number.
- Hide the helper column and write code to execute the hiding/showing.
Question: Which one of the following methods would you expect to be faster? Column B is the helper column and will always be contiguous.
Sub SetRowVisibility1()
Dim rowsToCheck As Range
With ActiveSheet
Set rowsToCheck = .Range(Range("B7"), Range("B7").End(xlDown))
End With
Dim needToShow As Range, needToShow_Showing As Range
Dim needToHide As Range, needToHide_Showing As Range
Set needToShow = rowsToCheck.SpecialCells(xlCellTypeFormulas, xlNumbers)
Set needToHide = rowsToCheck.SpecialCells(xlCellTypeFormulas, xlErrors)
On Error Resume Next
Set needToShow_Showing = needToShow.Offset(0, 1).SpecialCells(xlCellTypeVisible)
Set needToHide_Showing = needToHide.Offset(0, 1).SpecialCells(xlCellTypeVisible)
On Error GoTo 0
If Not needToHide_Showing Is Nothing Then
needToHide_Showing.EntireRow.Hidden = True
End If
If Not needToShow Is Nothing Then
If needToShow.Count <> needToShow_Showing.Count Then
needToShow.EntireRow.Hidden = False
End If
End If
End Sub
Sub SetRowVisibility2()
Dim rowsToCheck As Range
With ActiveSheet
Set rowsToCheck = .Range(Range("B7"), Range("B7").End(xlDown))
End With
Dim needToShow As Range, needToHide As Range
Dim cell As Range
For Each cell In rowsToCheck
If IsError(cell.Value) And (cell.EntireRow.Hidden = False) Then
If needToHide Is Nothing Then
Set needToHide = cell
Else
Set needToHide = Union(needToHide, cell)
End If
End If
If Not IsError(cell.Value) And (cell.EntireRow.Hidden = True) Then
If needToShow Is Nothing Then
Set needToShow = cell
Else
Set needToShow = Union(needToShow, cell)
End If
End If
Next cell
If Not needToHide Is Nothing Then needToHide.EntireRow.Hidden = True
If Not needToShow Is Nothing Then needToShow.EntireRow.Hidden = False
End Sub