我编写了以下代码来隐藏工作表使用范围内的空白行。代码工作得非常好。我已将此宏指定给工作表上的按钮。单击该按钮会隐藏使用范围内的空白行。
问题:如何修改代码以便单击相同的按钮反之?如果空白行被取消隐藏,则单击该按钮会隐藏它们;如果它们被隐藏,那么点击相同的按钮会取消隐藏它们?我想用一个按钮执行这两个程序。
Sub HideLLRows()
'This sub un/hides blank rows in EIRP LL
Application.ScreenUpdating = False
Dim LastRow As Long
Set EIRPLL = Sheets("EIRP LL")
LastRow = EIRPLL.UsedRange.Rows.Count
For i = 6 To LastRow
If EIRPLL.Range("B" & i) = "" Then
EIRPLL.Rows(i).Hidden = True
End If
Next
Application.ScreenUpdating = True
End Sub
答案 0 :(得分:3)
简单的答案是切换每个空白行的Hidden
状态
EIRPLL.Rows(i).Hidden = Not EIRPLL.Rows(i).Hidden
这样做的缺点是,如果用户更改了一个或多个空白行的隐藏状态,则此宏不会让您返回所有隐藏状态或所有可见状态。
另一种方法是根据找到的第一个空白设置可见性。
这是您重构的代码,还有一些额外的优化:
Dim
所有您的变量Hidden
属性Sub HideLLRows()
'This sub un/hides blank rows in EIRP LL
Application.ScreenUpdating = False
Dim i As Long
Dim EIRPLL As Worksheet
Dim NewState As VbTriState
Dim dat As Variant
Dim rws As Range
Dim LastRow As Long
Set EIRPLL = Sheets("EIRP LL")
With EIRPLL.UsedRange
LastRow = .Rows.Count - .Row + 1 ' in case used range doesn't start at row 1
dat = .Columns(2).Resize(LastRow, 1)
End With
NewState = vbUseDefault
With EIRPLL
For i = 6 To LastRow
If dat(i, 1) = "" Then
If NewState = vbUseDefault Then
NewState = Not .Rows(i).Hidden
End If
If rws Is Nothing Then
Set rws = Cells(i, 1)
Else
Set rws = Union(rws, Cells(i, 1))
End If
End If
Next
End With
rws.EntireRow.Hidden = NewState
Application.ScreenUpdating = True
End Sub