用于根据单元格值隐藏行的VBA宏

时间:2016-10-19 17:45:17

标签: excel vba excel-vba macros

我正在制作一张工作表,其中的部分根据单元格值(1-10之间)隐藏/显示多行。目前,我有一些嵌套的if语句。这使我的工作簿变得非常缓慢。有没有办法缩小这段代码?感谢。

If Range("B87").Value = 10 Then
        Rows("88:98").EntireRow.Hidden = False
    Else
    If Range("B87").Value = 9 Then
        Rows("98").EntireRow.Hidden = True
        Rows("88:97").EntireRow.Hidden = False
    Else
    If Range("B87").Value = 8 Then
        Rows("97:98").EntireRow.Hidden = True
        Rows("88:96").EntireRow.Hidden = False
    Else
    If Range("B87").Value = 7 Then
        Rows("96:98").EntireRow.Hidden = True
        Rows("88:95").EntireRow.Hidden = False
    Else
    If Range("B87").Value = 6 Then
        Rows("95:98").EntireRow.Hidden = True
        Rows("88:94").EntireRow.Hidden = False
    Else
    If Range("B87").Value = 5 Then
        Rows("94:98").EntireRow.Hidden = True
        Rows("88:93").EntireRow.Hidden = False
    Else
    If Range("B87").Value = 4 Then
        Rows("93:98").EntireRow.Hidden = True
        Rows("88:92").EntireRow.Hidden = False
    Else
    If Range("B87").Value = 3 Then
        Rows("92:98").EntireRow.Hidden = True
        Rows("88:91").EntireRow.Hidden = False
    Else
    If Range("B87").Value = 2 Then
        Rows("91:98").EntireRow.Hidden = True
        Rows("88:90").EntireRow.Hidden = False
    Else
    If Range("B87").Value = 1 Then
        Rows("90:98").EntireRow.Hidden = True
        Rows("88:89").EntireRow.Hidden = False
    Else
    If Range("B87").Value = 0 Then
        Rows("88:98").EntireRow.Hidden = True
    End If
    End If
    End If
    End If
    End If
    End If
    End If
    End If
    End If
    End If
    End If

3 个答案:

答案 0 :(得分:1)

我可能会尝试一个案例陈述。

哦,甚至使用ElseIf选项,它至少会减少EndIf语句的数量。

我认为案例代码如下所示:

选择范围(" B87")。值

Case "1"

Case "2"

...

结束选择

答案 1 :(得分:1)

你有很多基本相同的代码。我看了一下,试图让它更加算术,这缩短了代码。看看是否有效:

Sub t()
Dim myVal   As String
Dim mainRow As Long, tweakRow As Long
Dim hideRange As Range, showRange As Range
Dim row1 As Long, row2 As Long

mainRow = 98
myVal = Range("B87").Value

If myVal = 10 Then
    Rows(mainRow - 10 & ":" & mainRow - 10 + myVal).EntireRow.Hidden = False
ElseIf myVal >= 1 And myVal <= 9 Then
    tweakRow = mainRow - 10
    row1 = (mainRow - (9 - myVal))
    row2 = (mainRow - (10 - myVal))
    Set hideRange = Rows(row1 & ":" & mainRow).EntireRow
    Set showRange = Rows(tweakRow & ":" & row2).EntireRow

    Debug.Print "For a value of " & myVal & ", we will hide range: " & hideRange.Address & ", and show range: " & showRange.Address

    hideRange.Hidden = True
    showRange.Hidden = False
ElseIf myVal = 0 Then
    Rows(mainRow - 10 & ":" & mainRow).EntireRow.Hidden = True
End If

End Sub

答案 2 :(得分:1)

使用EntireRow或“EntireColumn Rows列”时,您无需使用when using

Rows("88:98").Hidden = True

If Range("B87").Value > 0 Then
    Rows(88).Resize(1 + Range("B87").Value).Hidden = False
End If