我试图将 Excel 中的行隐藏在 B 列中值为“P1”的行和 B 列中值为“P2”的行之间。我已经尝试过,令我自己感到羞耻的是,我使用了 Chatgpt 作为一部分,但我是现在卡住了。代码的一部分成功地隐藏了行,但是当我按下按钮时我无法让它们重新出现。我尝试过的一些事情被注释掉了,
Private Sub CommandButton1_Click()
Dim ws As Worksheet
Dim startRow As Long
Dim endRow As Long
Dim cell As Range
Dim Rng As Range
' Set the worksheet
Set ws = ThisWorkbook.Sheets("Calculatie")
' Find the start and end rows based on values in column B
For Each cell In ws.Range("B:B")
If cell.Value = "P1" And startRow = 0 Then
startRow = cell.Row
ElseIf cell.Value = "P2" And startRow <> 0 Then
endRow = cell.Row
Exit For
End If
Next cell
'Set Rng = Selection
'Set Rng = ws.Rows(startRow + 1 & ":" & endRow - 1)
'Set Rng = ws.Range("startRow", "endRow")
' Hide rows between startRow and endRow
If startRow > 0 And endRow > 0 Then
'If Rng.Hidden = True Then
'Selection.EntireRow.Hidden = True
ws.Rows(startRow + 1 & ":" & endRow - 1).EntireRow.Hidden = True
Else
'Selection.EntireRow.Hidden = False
'ws.Rows(startRow + 1 & ":" & endRow - 1).EntireRow.Hidden = False
MsgBox "Start or end value not found in column B"
End If
End Sub
我需要更改什么才能使其正常工作?
我尝试制定一个范围并更改隐藏值,但出现了错误...所以我把我放回原来有效的代码...
一种解决方法,用于检查
Hidden
之后的下一行 P1
状态并将工作表行状态设置为 False
,如下所示:
Private Sub CommandButton1_Click()
Dim ws As Worksheet
Dim startRow As Long
Dim endRow As Long
Dim cell As Range
Dim Rng As Range
' Set the worksheet
Set ws = ThisWorkbook.Sheets("Calculatie")
'Insertion start
Dim g as Long
On Error Resume Next
g = ws.Columns("B").Find("P1").Row
On Error GoTo 0
If Not IsEmpty(g) And rows(g + 1).Hidden = True Then
ws.rows.Hidden = False
Exit Sub
End If
'insertion End
' Find the start and end rows based on values in column B
For Each cell In ws.Range("B:B")
If cell.value = "P1" And startRow = 0 Then
startRow = cell.Row
ElseIf cell.value = "P2" And startRow <> 0 Then
endRow = cell.Row
Exit For
End If
Next cell
'Set Rng = Selection
'Set Rng = ws.Rows(startRow + 1 & ":" & endRow - 1)
'Set Rng = ws.Range("startRow", "endRow")
' Hide rows between startRow and endRow
If startRow > 0 And endRow > 0 Then
'If Rng.Hidden = True Then
'Selection.EntireRow.Hidden = True
ws.rows(startRow + 1 & ":" & endRow - 1).EntireRow.Hidden = True
Else
'Selection.EntireRow.Hidden = False
'ws.Rows(startRow + 1 & ":" & endRow - 1).EntireRow.Hidden = False
MsgBox "Start or end value not found in column B"
End If
End Sub
如果我理解正确,您想要切换行的可见性:首先单击按钮将隐藏它们,下次单击将再次显示它们。
所以你需要检查行是否已经隐藏。以下代码片段将执行此操作:它将“P1”下方第一行的
Hidden
属性保存到变量 (isAlreadyHidden) 中,并将行的 Hidden
属性设置为相反的 (Not isAlreadyHidden
)
If startRow > 0 And endRow > 0 Then
Dim isAlreadyHidden As Boolean
isAlreadyHidden = ws.Rows(startRow + 1).Hidden
ws.Rows(startRow + 1 & ":" & endRow - 1).EntireRow.Hidden = Not isAlreadyHidden
Else
MsgBox "Start or end value not found in column B"
End If