簡體   English   中英

VBA根據特定答案隱藏/取消隱藏行

[英]VBA Hide/Unhide Rows based on specific answers

我試圖根據特定的單元格值隱藏/取消隱藏行。 到目前為止,我的代碼有效並且在下面:但是,我也試圖顯示“是”“否”行之間的行。 例如,第11-15行如圖所示開始。 第15行的答案為“是”或“否”。 選擇“是”后,我需要顯示16-20。 但到目前為止,我只能顯示20(第8列是“是/否”的選擇,第11列是偏移量,第12列當前包含要跳轉到的數字...因此第15列第12列包含“ 20”。 。但我需要是16-20)。 我該如何解決? 謝謝

Private Sub Worksheet_Change(ByVal Target As Range)

If Target.Count > 1 Then

For Each cel In Target
       Call Worksheet_Change(cel)
       Next cel
End If
If Target.Column = 8 Then

   If LCase(Target.Value) = LCase(Target.Offset(, 3)) Then
   Cells(Target.Offset(, 4), 1).EntireRow.Hidden = False
Else

   Cells(Target.Offset(, 4), 1).EntireRow.Hidden = True

End If:  End If

End Sub

最簡單的方法是使用循環。 您想要做的是隱藏循環中的每一行,例如,此循環將隱藏行1-3

For i=1 to 3
    Rows(i).EntireRow.Hidden = True
Next

如果我正確理解您的設置,則第8列包含“是/否”。 第11列包含用於開始(取消)隱藏行的行偏移量。 第12列告訴您在哪里停止(取消隱藏)行。

我將使用以下表示法來指示單元格地址(行,列)

回到你的例子,如果(15,8)說“是”,那么你取消隱藏行16,17,18,19,20。 這意味着(15,11)將包含1,因為到達第16行的偏移量是current_row +1,其中當前行是15單元格(15,12)包含20,因為它是要跳轉到的最后一行。 只需將單元格(15,11)中的值用作循環的開始,並將單元格(15,12)中的值用作停止值

 Private Sub Worksheet_Change(ByVal Target As Range) 'defines some constants Const iYES_NO_COL = 8 Const iOFFSET_COL = 11 Const iSKIP_TO_COL = 12 If Target.Count > 1 Then For Each cel In Target Call Worksheet_Change(cel) Next cel End If ElseIf Target.Count = 1 Then 'im not sure what this does so i left it If Target.Column = 8 Then If LCase(Target.Value) = LCase(Target.Offset(, 3)) Then Cells(Target.Offset(, 4), 1).EntireRow.Hidden = False Else Cells(Target.Offset(, 4), 1).EntireRow.Hidden = True End If If (Target.Column = iYES_NO_COL) Then ' takes the current row + the value in the offset cell my_start = Target.Row + Cells(Target.Row, iOFFSET_COL).Value ' takes the value from the SKIP_TO_COL my_stop = Cells(Target.Row, iSKIP_TO_COL).Value 'target should be only one cell at this point, see if it 'contains the word no If (StrComp(Trim(LCase(Target.Value)), "no") = 0) Then 'hides all the rows between the start and stop value For i = my_start To mystop Rows(i).EntireRow.Hidden = True Next ElseIf (StrComp(Trim(LCase(Target.Value)), "yes") = 0) Then 'unhides all the rows between the start and stop value For i = my_start To mystop Rows(i).EntireRow.Hidden = False Next End If End If End Sub 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM