是否有更好的解决方案,以下代码

时间:2018-03-08 12:39:24

标签: excel vba

我目前正在添加一个隐藏的按钮,并显示不连续的行。虽然以下工作(在某种程度上)是一个更好的选择来调用行而不是下面列出的。

Sub Button7_Click()

    With Range("5:5, 7:7, 9:9, 11:11, 13:13, 15:15, 17:17, 19:19, 21:21,23:23, 25:25, 27:27, 29:29, 31:31, 33:33, 35:35, 37:37, 39:39, 41:41, 43:43, 45:45, 47:47, 49:49, 51:51, 53:53, 55:55, 63:63, 65:65, 67:67, 69:69, 71:71, 73:73, 75:75, 77:77, 79:79, 81:81, 85:85, 83:83")
        .Select
        .EntireRow.Hidden = Not .EntireRow.Hidden
    End With

End Sub

另外,如果我试图超出下面的范围,我会收到错误:

  

运行时错误' 1004':方法'范围'对象' _Global'失败

我不是excel的专家,因此您可以提供有关任何代码更改和实施的详细信息,我们将非常感激。

非常感谢提前

4 个答案:

答案 0 :(得分:3)

for x=5 to 85 step 2

rows(x).hidden=not rows(x).hidden

next x

答案 1 :(得分:1)

Sub Button7_Click()
For i = 5 to 83 step 2
    Rows(i).entireRow.Hidden = Not Rows(i).EntireRow.Hidden
Next i
End Sub

答案 2 :(得分:0)

您已达到可应用于范围对象的上限字符串长度,但有解决方法。

联盟的两种方法。首先是硬编码结构。

Sub Button7_Click()    
    With union(Range("5:5, 7:7, 9:9, 11:11, 13:13, 15:15, 17:17, 19:19, 21:21, 23:23"), _
               range("25:25, 27:27, 29:29, 31:31, 33:33, 35:35, 37:37, 39:39, 41:41"), _
               range("43:43, 45:45, 47:47, 49:49, 51:51, 53:53, 55:55, 63:63, 65:65"), _
               range("67:67, 69:69, 71:71, 73:73, 75:75, 77:77, 79:79, 81:81, 85:85"), _
               range("83:83, 85:85, 87:87, 89:89, 91:91, 93:93, 95:95, 97:97, 99:99"), _
               range("101:101, 103:103, 105:105, 107:107"))
    .EntireRow.Hidden = Not .EntireRow.Hidden
    End With
End Sub

然后使用优化循环。

Sub Button7_Click()
    dim r as long, rng as range
    set rng = range("5:5, 7:7, 9:9, 11:11, 13:13")
    for r = 10 to 1000 step 10
        set rng =  union(rng, range("5:5, 7:7, 9:9, 11:11, 13:13").offset(r, 0))
    next r
    rng.EntireRow.Hidden = Not rng.EntireRow.Hidden
End Sub

答案 3 :(得分:0)

我的0.02美分

Sub Button7_Click()
    Dim rng As Range, i As Long

    Set rng = Range("B1")
    For i = 5 To 83 Step 2
        Set rng = Union(rng, Cells(i, 1))
    Next i
    With Intersect(rng, Columns(1))
        .EntireRow.Hidden = Not .EntireRow.Hidden
    End With
End Sub