【问题标题】:Hiding multiple rows based on cell values根据单元格值隐藏多行
【发布时间】:2015-01-17 01:24:20
【问题描述】:

我有一个算法可以很好地隐藏所有行,在指定的命名范围内,给定行的值为 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 个报告运行。

【问题讨论】:

  • 考虑使用自动过滤器
  • 我认为Ra_LignesAZero 范围只有 1 列?
  • 是的。这也可能是一个金发的时刻,但我确实可以使用自动过滤器。它只是看起来不那么干净。也许我想多了。

标签: vba excel excel-2007


【解决方案1】:

以下是一些优化:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多