VBA基于特定答案隐藏/取消隐藏行

我正试图隐藏/取消隐藏基于特定单元格的行。 到目前为止,我的代码的工作原理如下:但是,我也试图显示“是”“否”行之间的行。 例如,第11-15行如图所示开始。 第15行有“是”或“否”的答案。 select“是”后,我需要显示16-20。 但到目前为止,我只能显示20(第8列是select是/否,第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包含一个行开始(un)隐藏行的偏移量。 列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