行隐藏宏慢在丝带excel但在'97快速

时间:2016-02-20 14:18:37

标签: excel vba excel-vba

我有以下sub,它是由工作表上某个单元格的更改触发的。它根据A列中的值隐藏/取消隐藏行(A列中的公式链接到更改的单元格,这就是我需要在每次单元格更改时查看要隐藏的内容的原因)。我在Excel 97上可以顺利地工作,但在新版本上需要花费几秒钟的时间,我很难搞清楚导致这种差异的原因。我认为这是因为宏在某个时刻遍历所有行,但我无法看到发生的位置。任何建议将不胜感激! 大卫

Private Sub Worksheet_Change(ByVal Target As Range)
Dim i, lastrow

'------------------------setting target--------------------
    If Target.Address(True, True) = Range("futamido").Address Then
        Application.ScreenUpdating = False
        Application.PrintCommunication = False
'------------------------unprotect sheet----------------------------------------
        If Worksheets("calculation").ProtectContents = True Then
            Worksheets("calculation").Unprotect ("password")
        End If
'-------------------------review hiding settings------------------------
        lastrow = Worksheets("calculation").Range("a1:a1000").Find("*", Cells(1, 1), xlFormulas, , xlByRows, xlPrevious).Row
        For i = 1 To lastrow
            If Worksheets("calculation").Cells(i, 1) = 1 Then
                Worksheets("calculation").Rows(i).EntireRow.Hidden = False
            Else
                Worksheets("calculation").Rows(i).EntireRow.Hidden = True
            End If
        Next i
'------------------------reprotect sheet if other sheets are protected----------------------------------------
        If Worksheets("start").ProtectContents = True Then
            Worksheets("calculation").Protect DrawingObjects:=True, Contents:=True, Scenarios:= _
            True, Password:="password"
        End If

        Application.PrintCommunication = True
        Application.ScreenUpdating = True
    End If
End Sub

1 个答案:

答案 0 :(得分:0)

请尝试更改代码的第3部分:

....
'-------------------------review hiding settings------------------------
  lastrow = Worksheets("calculation").Range("a1:a1000").Find("*", Cells(1, 1), xlFormulas, , xlByRows, xlPrevious).Row
  Dim rngHide As Range, rngShow As Range
  For i = 1 To lastrow
    If Worksheets("calculation").Cells(i, 1) = 1 Then
      If rngShow Is Nothing Then
        Set rngShow = Worksheets("calculation").Rows(i)
      Else
        Set rngShow = Union(rngShow, Worksheets("calculation").Rows(i))
      End If
    Else
      If rngHide Is Nothing Then
        Set rngHide = Worksheets("calculation").Rows(i)
      Else
        Set rngHide = Union(rngHide, Worksheets("calculation").Rows(i))
      End If
    End If
  Next i
  rngShow.EntireRow.Hidden = False
  rngHide.EntireRow.Hidden = True
'------------------------reprotect sheet if other sheets are protected----------------------------------------
....

并判断是否加快了代码速度:)

也像Jeeped间接提到的那样:如果没有真正需要关闭它,请注释Application.PrintCommunication