vba - 根据单元格值隐藏多行

标签 vba excel excel-2007

我有一个算法可以很好地隐藏所有行,在指定的命名范围内,给定行的值为 0。这很简单:

Public Sub MasquerLignesAZeroRapport(rap As Worksheet)
    Dim cell As Range
    rap.Rows.Hidden = False

    For Each cell In rap.Range("Ra_LignesAZero")
        If Round(cell.Value, 0) = 0 Then
            cell.EntireRow.Hidden = True
        End If
    Next cell
End Sub

但是,即使关闭计算和屏幕更新,这也需要一些时间,并且我尝试了不同的其他方法但没有成功(使用过滤器并隐藏所有可见行但删除过滤器会取消隐藏行,设置行高为 0)。

有更快的选择吗?我可以忍受这种缓慢的算法,但这将是一个可喜的改进,因为这个宏可以在一次运行中针对 1-6 个报告运行。

最佳答案

以下是一些优化:

Public Sub MasquerLignesAZeroRapport(rap As Worksheet)
'Optimization #1: as you pointed out, turning off calculations
' and screen updating makes a difference.
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False

    rap.Rows.Hidden = False

    'Optimization #2: instead of loading each cell as a range,
    ' with all the associated properties, load JUST the values
    ' into a 2 dimensional array.
    Dim values() As Variant
    values = rap.Range("Ra_LignesAZero")  

    For r = 1 To UBound(values, 1)
        For c = 1 To UBound(values, 2)
            If Round(values(r,c), 0) = 0 Then
                rap.Rows(r).Hidden = True
                'Optimization #3: if we have already determined
                ' that the row should be hidden, no need to keep
                ' looking at cells in the row - might as well break out of the For:
                Exit For 
            End If
        Next
    Next
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
End Sub

关于vba - 根据单元格值隐藏多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27018324/

相关文章:

excel - VBA 在 OSX 上获取用户名(或 Environ ("username"的 Mac 替代方案))

vba - 当情况为真时如何选择单元格

excel - 使用On Error Goto尝试查找为什么我遇到错误

Excel 宏 - 任何人都可以解释这一点吗?

c# - 如何识别工作表已最小化?

forms - 用户表单 VBA 位置 - 向前和向后

python - 使用 Openpyxl 将边框应用于单元格范围

vba - First.Cells(i,1) 是如何工作的?

excel - 从 Excel VBA UDF 调用时,Range.Precedents 返回范围而不是其先例。有解决方法吗?

excel - 如何更改轴值标签方向?