简体   繁体   English

根据单元格值隐藏行非常慢

[英]Hiding rows based on cell value is very slow

I have working code to hide/unhide rows depending on the corresponding cell value.我有工作代码可以根据相应的单元格值隐藏/取消隐藏行。

This is a list of materials and there is a 'finalize' button.这是一个材料列表,有一个“完成”按钮。 You press the button and any row where quantity = 0 should be hidden.您按下按钮,应隐藏数量 = 0 的任何行。

There are 400+ lines and I can see the lines disappear.有 400 多行,我可以看到这些行消失了。 It is processing roughly 20 lines per second which makes it over 20 seconds to do the list.它每秒处理大约 20 行,这使得完成列表的时间超过 20 秒。 The list will double every few months.这份名单每隔几个月就会翻一番。

Is there another method that will hide the lines faster?有没有另一种方法可以更快地隐藏线条?

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

I was just typing up as appeared in comments.我只是像评论中那样打字。 Use Union to gather qualifying ranges and hide in one go.使用 Union 收集符合条件的范围并一次性隐藏。 I am not sure why you are doing a double test.我不确定您为什么要进行双重测试。 Wouldn't = 0 be sufficient? = 0 不够吗? Or as @Marcucciby2 queries, did you intend an Or?或者作为@Marcucciby2 查询,您是否打算使用 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.正如其他答案中所述,您可以通过切换 ScreenUpdating、pageBreaks 等内容并切换到手动计算模式来进行一些优化。

If possible, get rid of that ActiveSheet reference and use the actual workbook and worksheet references.如果可能,去掉那个 ActiveSheet 引用并使用实际的工作簿和工作表引用。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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