VBA EXCEL - 工作表开放宏的小代码优化

时间:2017-07-05 15:48:08

标签: excel vba performance excel-vba

我希望加速我在excel中的on-worksheet open macro。

每次打开工作表时,我都希望它自动调整x行,然后隐藏任何包含0的行。

宏工作正常,但我认为必须有更好/更快的方法来隐藏所有相关的行。任何帮助将不胜感激。

Private Sub Worksheet_Activate()
    Rows("14:859").EntireRow.AutoFit
Application.ScreenUpdating = False
Dim c As Range
    For Each c In Range("O1:O859").Cells
        If c.Value = "0" Then
            c.EntireRow.Hidden = True
        End If
    Next c
Application.ScreenUpdating = True
End Sub

1 个答案:

答案 0 :(得分:0)

试试这个版本:

Option Explicit

Private Sub Worksheet_Activate()
  Const LAST_ROW = 859
  Const CL = 15             'O column
  Const RO = 14
  Const HIDE_ROWS = True    'or False

  Dim ur As Variant, hr As Range, R As Long

  Application.ScreenUpdating = False

  Rows(RO & ":" & LAST_ROW).EntireRow.AutoFit

  ur = Range(Cells(1, CL), Cells(LAST_ROW, CL))
  For R = 1 To LAST_ROW
    If Len(ur(R, 1)) = 0 Then Exit For
    If ur(R, 1) = 0 Then
        If hr Is Nothing Then Set hr = Cells(R, 1) Else: Set hr = Union(hr, Cells(R, 1))
    End If
  Next
  hr.EntireRow.Hidden = HIDE_ROWS

  Application.ScreenUpdating = True
End Sub