Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a small Excel VBA Macro is running extremely slow

Tags:

excel

vba

I am writing a short macro to hide all customers that have no current sales for the current year. The YTD sales are in the K column (specifically K10-250). Those cells use a vlookup to pull data from another tab where we dump data. My question is why on earth would this macro take 10-15minutes to run? I have a similar macro on another spreadsheet that takes only 2-3 minutes for over 1,500 rows. I have already turned off screen updating. I can't think of anything else that would speed it up.

   Sub HideNoSlackers()
'
' HideNoSlackers Macro
'

'
Application.ScreenUpdating = False
'
 Sheets("CONSOLIDATED DATA").Select
 Dim cell As Range
 For Each cell In Range("K10:K250")
   If cell.Value = 0 Then
     cell.EntireRow.Hidden = True
   Else
     cell.EntireRow.Hidden = False
   End If
 Next
End Sub
like image 566
B-Rell Avatar asked Dec 15 '22 06:12

B-Rell


2 Answers

You might want the calculation to be set Manual before hiding the rows? Also you can get rid of If statements in your case. Try this:

Sub HideNoSlackers()
    Dim cell As Range, lCalcState As Long

    Application.ScreenUpdating = False
    ' Record the original Calculation state and set it to Manual
    lCalcState = Application.Calculation
    Application.Calculation = xlCalculationManual
    For Each cell In ThisWorkbook.Worksheets("CONSOLIDATED DATA").Range("K10:K250")
        cell.EntireRow.Hidden = (cell.Value = 0)
    Next
    ' Restore the original Calculation state
    Application.Calculation = lCalcState
    Application.ScreenUpdating = True ' Don't forget set ScreenUpdating back to True!
End Sub
like image 80
PatricK Avatar answered Dec 30 '22 21:12

PatricK


Sub HideNoSlackers()
 Dim cell As Range, rng As Range, rngHide As Range

    Set rng = Sheets("CONSOLIDATED DATA").Range("K10:K250")
    rng.EntireRow.Hidden = False

    For Each cell In rng.Cells
        If cell.Value = 0 Then
            If Not rngHide Is Nothing Then
                Set rngHide = Application.Union(rngHide, cell)
            Else
                Set rngHide = cell
            End If
        End If
    Next

    If Not rngHide Is Nothing Then rngHide.EntireRow.Hidden = True
End Sub
like image 33
Tim Williams Avatar answered Dec 30 '22 20:12

Tim Williams