I am looking for a code to hide empty rows for a specific range of columns by using a toggle button. I have a table starting in P9 to U71 and I would like a code to hide any row that does not contain any data in that specific table. I have tried several codes with the most recent posted below but this code is hiding based on the values in column U and even if there was data in that same row but in a different column. I should note that I have zero experience with coding and thus I thank you for any assistance with this issue.
Sub Worksheet_Activate()
Dim r As Range, c As Range
Set r = Range("q9:u71")
Application.ScreenUpdating = False
For Each c In r
If Len(c.Text) = 0 Then
c.EntireRow.Hidden = True
Else
c.EntireRow.Hidden = False
End If
Next c
Application.ScreenUpdating = True
End Sub
Try the next code, please:
Sub Worksheet_Activate()
Dim i As Long, rngH As Range
For i = 9 To 71
If WorksheetFunction.CountA(Range("P" & i & ":U" & i)) = 0 Then
If rngH Is Nothing Then
Set rngH = Range("P" & i)
Else
Set rngH = Union(rngH, Range("P" & i))
End If
End If
Next i
If Not rngH Is Nothing Then rngH.EntireRow.Select '.Hidden = True
End Sub
It only selects the rows to be hidden. If it works as you need, put .Hidden = True
instead of Select
.
It should be very fast, placing the empty cells in a range and hiding the EntireRow
at once, at the end.
Now, if the cells in the processed range are modified by code and some (already) hidden cells receive a value, don't you need to make them visible?
I will close my laptop. If the answer to my above question is yes, please use the next code. If not, do not use it...
Sub Worksheet_Activate()
Dim r As Range, i As Long, rngH As Range, rngV As Range
For i = 9 To 71
If WorksheetFunction.CountA(Range("P" & i & ":U" & i)) = 0 Then
If rngH Is Nothing Then
Set rngH = Range("P" & i)
Else
Set rngH = Union(rngH, Range("P" & i))
End If
Else
If rngV Is Nothing Then
Set rngV = Range("P" & i)
Else
Set rngV = Union(rngV, Range("P" & i))
End If
End If
Next i
If Not rngH Is Nothing Then rngH.EntireRow.Hidden = True
If Not rngV Is Nothing Then rngV.EntireRow.Hidden = False
End Sub