我对excel-macros还是很陌生,因此我不知道以下宏导致我的excel崩溃的原因(在Mac和Win上)。因此,我想尝试简化公式,将许多if简化为一个公式。能否请你帮忙?
Private Sub Worksheet_Change(ByVal Target As Range)
Dim KeyCells As Range
Set KeyCells = Range("B8")
If Range("B8").Value = "0" Then
Rows("14:24").EntireRow.Hidden = True
Rows("13").EntireRow.Hidden = False
Range("B14:B24").Clear
Worksheets("Sheet1").Range("B9").Value = "Open"
End If
If Range("B8").Value = "1" Then
Rows("15:24").EntireRow.Hidden = True
Rows("13:14").EntireRow.Hidden = False
Worksheets("Sheet1").Range("B9").Value = "Open"
Range("B15:B24").Clear
End If
If Range("B8").Value = "2" Then
Rows("16:24").EntireRow.Hidden = True
Rows("13:15").EntireRow.Hidden = False
Worksheets("Sheet1").Range("B9").Value = "Open"
Range("B16:B24").Clear
End If
If Range("B8").Value = "3" Then
Rows("17:24").EntireRow.Hidden = True
Rows("13:16").EntireRow.Hidden = False
Worksheets("Sheet1").Range("B9").Value = "Open"
Range("B17:B24").Clear
End If
If Range("B8").Value = "4" Then
Rows("18:24").EntireRow.Hidden = True
Rows("13:17").EntireRow.Hidden = False
Range("B18:B24").Clear
End If
If Range("B8").Value = "5" Then
Rows("19:24").EntireRow.Hidden = True
Rows("13:18").EntireRow.Hidden = False
Range("B19:B24").Clear
End If
If Range("B8").Value = "6" Then
Rows("20:24").EntireRow.Hidden = True
Rows("13:19").EntireRow.Hidden = False
Range("B20:B24").Clear
End If
If Range("B8").Value = "7" Then
Rows("21:24").EntireRow.Hidden = True
Rows("13:20").EntireRow.Hidden = False
Range("B21:B24").Clear
End If
If Range("B8").Value = "8" Then
Rows("22:24").EntireRow.Hidden = True
Rows("13:21").EntireRow.Hidden = False
Range("B22:B24").Clear
End If
If Range("B8").Value = "9" Then
Rows("23:24").EntireRow.Hidden = True
Rows("13:22").EntireRow.Hidden = False
Range("B23:B24").Clear
End If
If Range("B8").Value = "10" Then
Rows("24").EntireRow.Hidden = True
Rows("13:23").EntireRow.Hidden = False
Range("B24").Clear
End If
If Range("B8").Value = "11" Then
Rows("13:24").EntireRow.Hidden = False
End If
End Sub
如您所见,公式的逻辑是:B8的值越高,隐藏的13和24之间的行越少。 B8的值越小,隐藏的行越多,并且清除隐藏的行的值。
最佳答案
您可以首先将整个行13-34设置为可见(.Hidden = False
),然后根据Range("B8").Value
中的值设置要隐藏的行数。
我也认为您只想在Range(“ B8”)中的值更改时才运行此代码,因此可以在Worksheet_Change
事件中添加一行以检查:If Not Intersect(Target, Range("B8")) Is Nothing Then
。
码
Private Sub Worksheet_Change(ByVal Target As Range)
Application.EnableEvents = True
If Not Intersect(Target, Range("B8")) Is Nothing Then ' <-- run this code only when changing the value of B8
Select Case Target.Value
Case 0 To 11
Range("B13:B24").EntireRow.Hidden = False
Range("B" & 14 + Target.Value & ":B24").EntireRow.Hidden = True
Range("B" & 14 + Target.Value & ":B24").Clear
Case Else
'do nothing
End Select
End If
Application.EnableEvents = True
End Sub