VBA代码隐藏和取消隐藏多个工作表上的空行

时间:2017-09-03 02:55:17

标签: vba

我有问题让这段代码工作 - 非常感谢任何帮助!我知道问题与第一行有关...我在此代码上面有一个Private Sub Worksheet_Change(ByVal Target As Range)来解决我需要VBA代码的其他元素。

Private Sub HideAndUnhideRowsInOtherWorksheet()
    For Each c In Worksheets("FlatStage").Range("A7:A32")
        If c.Value = "" Then
            c.EntireRow.Hidden = True
        Else
            c.EntireRow.Hidden = False
        End If
    Next
    For Each c In Worksheets("Efficiency").Range("A7:A32")
        If c.Value = "" Then
            c.EntireRow.Hidden = True
        Else
            c.EntireRow.Hidden = False
        End If
    Next
    For Each c In Worksheets("DayRate").Range("A7:A10,A14:A22,A25:A25,A28:A39")
        If c.Value = "" Then
            c.EntireRow.Hidden = True
        Else
            c.EntireRow.Hidden = False
        End If
    Next
    For Each c In Worksheets("AddServ").Range   ("A6:A8,A10:A11,A13:A17")
        If c.Value = "" Then
            c.EntireRow.Hidden = True
        Else
            c.EntireRow.Hidden = False
        End If
    Next
    For Each c In Worksheets("Enhancement").Range("A6:A7")
        If c.Value = "" Then
            c.EntireRow.Hidden = True
        Else
            c.EntireRow.Hidden = False
        End If
    Next
End Sub

1 个答案:

答案 0 :(得分:0)

如果您拨打上述Worksheet_Change()中的代码,它应该可以使用,但是如果您从其他模块调用您的Sub,它将无法显示,因为它被声明为 Private (对于该特定模块)

您需要做的就是将Private更改为 Public
(或将其移至新的通用模块并将其设为 Public

另一方面,屏幕在执行时可能会闪烁 要解决此问题,请在循环之前关闭ScreenUpdating,然后在

之后重新打开它

但您也可以减少代码,以便更容易维护:

Option Explicit

Public Sub HideAndUnhideRowsInOtherWorksheet()
    Application.ScreenUpdating = False

    ToggleRows Worksheets("FlatStage").Range("A7:A32")
    ToggleRows Worksheets("Efficiency").Range("A7:A32")
    ToggleRows Worksheets("DayRate").Range("A7:A10,A14:A22,A25:A25,A28:A39")
    ToggleRows Worksheets("AddServ").Range("A6:A8,A10:A11,A13:A17")
    ToggleRows Worksheets("Enhancement").Range("A6:A7")

    Application.ScreenUpdating = True
End Sub

Private Sub ToggleRows(ByRef colRng As Range)
    If Not colRng Is Nothing Then
        Dim c As Range
        For Each c In colRng
            c.EntireRow.Hidden = Len(c.Value2) = 0
        Next
    End If
End Sub

或者,如果您可以使用AutoFilter,则更小更快:

Private Sub FilterRows(ByRef colRng As Range)
    If Not colRng Is Nothing Then
        colRng.Parent.UsedRange.Columns(colRng.Column).AutoFilter 'Filter symbol in top cell
        colRng.AutoFilter Field:=1, Criteria1:="<>"
    End If
End Sub

此子将取消隐藏所有工作表中的所有行

Public Sub UnhideAllRowsInAllWorksheets()
    Dim ws As Worksheet
    For Each ws In Worksheets
        With ws.UsedRange
            If ws.AutoFilterMode Then .AutoFilter   'ws.ShowAllData
            .Rows.EntireRow.Hidden = False
        End With
    Next
End Sub