VBA问题 - 遍历每个工作表

时间:2016-09-21 20:10:15

标签: excel vba loops

我有一个带有循环逻辑的宏,我从另一个stackoverflow / ms支持页面复制了,但它似乎不起作用。

我对VBA没有经验,因此我无法弄清楚为什么'循环通过所有工作表'部分无效。

任何人都可以看看我的代码并告诉我如何修复它?

Sub HideEmptyRows()
    Dim rngName As Range
    Dim cell As Range
    Dim ws_count As Integer
    Dim i As Integer

    ws_count = ActiveWorkbook.Worksheets.Count
    For i = 1 To ws_count
        Application.ScreenUpdating = False
        For Each Current In Worksheets
            ' This code hides the adv and group merch rows
            For Each cell In Range("eq29", "eq51")
                If cell.Value = 0 Then
                    cell.EntireRow.Hidden = True
                    Else
                    cell.EntireRow.Hidden = False
                End If

            Next cell

            ' This code hides the consulting rows
            For Each cell In Range("eq61", "eq172")
                If cell.Value = 0 Then
                    cell.EntireRow.Hidden = True
                    Else
                    cell.EntireRow.Hidden = False
                End If
            Next cell
        Next

    Application.ScreenUpdating = True
    Next i
End Sub

1 个答案:

答案 0 :(得分:1)

根据我的评论:

您尚未将任何范围对象分配给父工作表,因此它仅适用于活动工作表。仅仅因为您正在循环,不会自动将工作表分配给这些范围。您需要将Current.放在所有范围对象的前面。

外环不是必需的。

我重写了隐藏的逻辑以节省一些输入:

Sub HideEmptyRows()

    Dim rngName As Range
    Dim cell As Range
    Dim current As Worksheet


    Application.ScreenUpdating = False
    For Each current In Worksheets
        ' This code hides the adv and group merch rows
        For Each cell In current.Range("EQ29:EQ51")
            cell.EntireRow.Hidden = cell.Value = 0
        Next cell

        ' This code hides the consulting rows
        For Each cell In current.Range("EQ61:EQ172")
            cell.EntireRow.Hidden = cell.Value = 0
        Next cell
    Next

    Application.ScreenUpdating = True

End Sub