VBA EXCEL Hiding rows based on cell value is very slow

空扰寡人 提交于 2019-12-12 16:21:56

问题


I have the code below to hide/unhide entire rows depending on the corresponding cell value (hide if it's 0) and it works fine.

This is a list of material and there is a 'finalize' button. At the end of the list you press the button and any item that has a quantity = 0 should hide this relevant row.

It works fine. But the problem is that it's very slow. As you can see it's 400+ lines and I can literally see as the lines disappear. It's processing roughly 20 lines per second which makes it over 20 seconds to do the list. And the list will double every few months.

So the question is - is there any other method that will hide the relevant lines in an instant or at least faster that it currently is?

Thanks a lot!

Hide:

Public Sub HideRows()
Dim cell As Range
    For Each cell In ActiveSheet.Range("H18:H469")
    cell.EntireRow.Hidden = (cell.Value = 0 And cell.Value <> "")
Next cell
End Sub

Unhide:

Public Sub UnhideRows()
Dim cell As Range
    For Each cell In ActiveSheet.Range("H18:H469")
    If (cell.Value = 0 And cell.Value <> "") Then cell.EntireRow.Hidden = False
    Next cell
End Sub

回答1:


I was just typing up as appeared in comments. Use Union to gather qualifying ranges and hide in one go. I am not sure why you are doing a double test. Wouldn't = 0 be sufficient? Or as @Marcucciby2 queries, did you intend an Or?

And as mentioned in other answer, you can do some optimization by switching of things like ScreenUpdating, pageBreaks and switch to manual calculation mode.

If possible, get rid of that ActiveSheet reference and use the actual workbook and worksheet references.

Option Explicit
Public Sub HideRows()
    Dim cell As Range, unionRng As Range
    For Each cell In ActiveSheet.Range("H18:H469")
        If cell.Value = 0 Then
            If Not unionRng Is Nothing Then
                Set unionRng = Union(unionRng, cell)
            Else
                Set unionRng = cell
            End If
        End If
    Next
    If Not unionRng Is Nothing Then unionRng.EntireRow.Hidden = True
End Sub



回答2:


Turn off screen updating and manual calculations at the start of your code. Be sure to turn if back on at the end of your code.

    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual
    '...your code...
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True


来源:https://stackoverflow.com/questions/53121616/vba-excel-hiding-rows-based-on-cell-value-is-very-slow

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!