繁体   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