我有两个切换按钮,一个用于隐藏一些行(在 B 列中标记为 2),另一个用于隐藏其他行(在 B 列中标记为 3)该按钮上周可以工作,但今天早上它停止了。
切换按钮更新其名称(即“隐藏”变为“显示”),但行本身保持不隐藏状态。
我对 VBA 非常缺乏经验 - 该代码是从各种在线 excel 帮助中抄袭的。因此,如果能以简单而详细的步骤解释任何帮助,那将是一个巨大的帮助。
提前致谢!
Private Sub ToggleButton1_Click()
Dim ws As Worksheet
Dim lastRow As Long
Dim i As Long
Set ws = ThisWorkbook.Sheets("Interim HSAP") ' Change to your sheet name
lastRow = ws.Cells(ws.Rows.Count, "B").End(xlUp).Row
For i = 8 To lastRow
If ws.Cells(i, "B").Value = 2 Then
ws.Rows(i).Hidden = ToggleButton1.Value
End If
Next i
' Update the button caption
If ToggleButton1.Value Then
ToggleButton1.Caption = "Show Milestones"
Else
ToggleButton1.Caption = "Hide Milestones"
End If
End Sub
Private Sub ToggleButton2_Click()
Dim ws As Worksheet
Dim lastRow As Long
Dim i As Long
Set ws = ThisWorkbook.Sheets("Interim HSAP") ' Change to your sheet name
lastRow = ws.Cells(ws.Rows.Count, "B").End(xlUp).Row
For i = 8 To lastRow
If ws.Cells(i, "B").Value = 3 Then
ws.Rows(i).Hidden = ToggleButton2.Value
End If
Next i
' Update the button caption
If ToggleButton2.Value Then
ToggleButton2.Caption = "Show Actions"
Else
ToggleButton2.Caption = "Hide Actions"
End If
End Sub
当我第一次安装按钮时,我尝试返回到电子表格的先前版本,并且它们使用类似的代码。 (这是在我进行一系列更改以获得我想要的确切行为之前,但据我所知,它们非常相似)
您的代码对我来说工作正常,所以您可能已经更改了某些内容,并且您的工作表设置不再与您的代码匹配。
这是一个简化版本,它将通用逻辑放入单独的方法中。
Option Explicit
Private Sub ToggleButton1_Click()
HideShowRows ToggleButton1, 2, "Milestones"
End Sub
Private Sub ToggleButton2_Click()
HideShowRows ToggleButton2, 3, "Actions"
End Sub
Sub HideShowRows(tb As ToggleButton, checkVal, lbl As String)
Const CHECK_COL As String = "B" 'col with values to be matched
Dim i As Long
'check the rows.... `Me` = the worksheet for the code module
For i = 8 To Me.Cells(Me.Rows.Count, CHECK_COL).End(xlUp).Row
If Me.Cells(i, CHECK_COL).Value = checkVal Then
Me.Rows(i).Hidden = tb.Value
End If
Next i
'update the caption
tb.Caption = IIf(tb.Value, "Show", "Hide") & " " & lbl
End Sub