简体   繁体   中英

VBA EXCEL - Small code optimization for on-worksheet open macro

I am looking to speed up an on-worksheet open macro I have in excel.

Every time the worksheet is opened, I would like it to autofit x rows and then hide any rows that have a 0 in it.

The macro works fine, but I think there must be a better/faster way to hide all relevant rows. Any help would be appreciated.

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

Try this version:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM