我已经编写了VBA代码来隐藏工作簿中4个不同选项卡中的特定范围。我正在向代码添加另一个范围,该范围将根据4个不同选项卡中每个区域中相同范围内的单元格值隐藏行。如果B9-B13范围内的单元格为空,则在每个标签上隐藏该特定行。
这是我当前的代码:
Sub HideRowsSummary()
Dim wsMySheet As Worksheet
Dim lngMyRow As Long
Application.ScreenUpdating = False
For Each wsMySheet In ThisWorkbook.Sheets
Select Case wsMySheet.Name
Case Is = "Summary 1", "Summary (2)", "Summary (3)", "Summary (4)"
For lngMyRow = 73 To 24 Step -1 'Need to work backwards through the rows when hiding or deleting
If Len(wsMySheet.Range("A" & lngMyRow)) = 0 Then
wsMySheet.Range("A" & lngMyRow).EntireRow.Hidden = True
Else
wsMySheet.Range("A" & lngMyRow).EntireRow.Hidden = False
End If
Next lngMyRow
End Select
Next wsMySheet
Application.ScreenUpdating = True
End Sub
感谢您的光临!
答案 0 :(得分:1)
例如上一循环之后的以下内容?使用“联合”将合格的行(如果全部都放在同一张纸中)聚集在一起并一路隐藏起来,效率更高。这样,您可以从两个循环中收集合格行(也可以将循环合并到其中),并一次性隐藏所有行。
For lngMyRow = 13 To 9 Step -1 'Need to work backwards through the rows when hiding or deleting
wsMySheet.Range("B" & lngMyRow).EntireRow.Hidden = (wsMySheet.Range("B" & lngMyRow) = vbNullString)
Next lngMyRow
感谢@ScottCraner指出那里非常好的简写方式。
带有范围联合的两个循环可能看起来像(未经测试):
Option Explicit
Public Sub HideRowsSummary()
Dim wsMySheet As Worksheet
Dim lngMyRow As Long, unionRng As Range
Application.ScreenUpdating = False
For Each wsMySheet In ThisWorkbook.Sheets
Select Case wsMySheet.NAME
Case Is = "Summary 1", "Summary (2)", "Summary (3)", "Summary (4)"
With wsMySheet
.Range("A9:A13, A24:A74").EntireRow.Hidden = False
For lngMyRow = 9 To 13
If .Range("B" & lngMyRow) = vbNullString Then
If Not unionRng Is Nothing Then
Set unionRng = Union(unionRng, .Range("B" & lngMyRow))
Else
Set unionRng = .Range("B" & lngMyRow)
End If
End If
Next lngMyRow
For lngMyRow = 24 To 73
If Len(.Range("A" & lngMyRow)) = 0 Then
If Not unionRng Is Nothing Then
Set unionRng = Union(unionRng, .Range("A" & lngMyRow))
Else
Set unionRng = .Range("A" & lngMyRow)
End If
End If
Next lngMyRow
End With
End Select
If Not unionRng Is Nothing Then unionRng.EntireRow.Hidden = True
Set unionRng = Nothing
Next wsMySheet
Application.ScreenUpdating = True
End Sub