【问题标题】:Faster way to hide empty rows隐藏空行的更快方法
【发布时间】:2014-06-06 09:26:58
【问题描述】:

我试图隐藏 A 列中单元格的 为空白(即空)的所有行。我试图使用以下代码:

Range("A7:A117").SpecialCells(xlCellTypeBlanks).EntireRow.Hidden = True

但是,A 列中的每个单元格都有一个VLOOKUP 公式,xlCellTypeBlanks 认为一个单元格有一个公式,但没有值,不是为空白。

所以我尝试使用以下代码,但是速度非常慢。

For i = 17 To 117
  If ActiveSheet.Cells(i, 1) = "" Then
    ActiveSheet.Cells(i, 1).EntireRow.Hidden = True
End If

如何加快速度?

【问题讨论】:

  • 您是否关闭了屏幕更新?我发现如果你在运行它之前设置application.screenupdating = false,然后再设置application.screenupdating = True,那么使用for循环就足够快了。对我来说缓慢的部分是在每行更改后更新屏幕
  • 我喜欢IsEmpty,就像If IsEmpty(Sheet1.Cells(i, 1)) Then一样

标签: excel vba excel-formula excel-2010


【解决方案1】:

你为什么不试试 AutoFilter:

Range("A7:A117").AutoFilter 1, "<>", , , False

【讨论】:

  • + 1 是的 Autofilter 是比循环更快的方法 :)
【解决方案2】:

缓慢的不是 for 循环,而是每次发生变化时您都在更新屏幕(这会占用相当多的处理能力,因此会减慢一切)。如果您在隐藏行之前关闭屏幕更新,然后在它只更新一次之后重新打开它,脚本将运行得更快。我尝试了 100 行,几乎是即时的。

Sub hideEmptyRows()

Application.ScreenUpdating = False

For i = 1 To 117
  If ActiveSheet.Cells(i, 1) = "" Then
    ActiveSheet.Cells(i, 1).EntireRow.Hidden = True
End If
Next i

Application.ScreenUpdating = True

End Sub

【讨论】:

  • 您可以通过将空白单元格写入循环内的范围(使用联合)并仅针对串联范围调用一个 EntireRow.Hidden 调用来使其更快。
【解决方案3】:
Range("A7:A117").AutoFilter 1, "<>", , , False

它会隐藏空单元格,但如果您尝试用鼠标取消隐藏,则无法

【讨论】:

  • 什么意思?
  • 看看下面 L42 的回答。
【解决方案4】:

这是一个没有自动过滤器的答案:

Dim totalRange As Range
ActiveSheet.Range("A17:A117").Hidde = false


For Each cell In ActiveSheet.Range("A17:A117")
   If cell = "" And totalRange Is Nothing Then
        Set totalRange = cell
   ElseIf cell = "" Then
        Set totalRange = Application.union(totalRange, cell)
   End If
Next

If Not totalRange Is Nothing Then
    totalRange.EntireRow.Hidden = True
End If

【讨论】:

    猜你喜欢
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 2013-06-30
    • 2011-01-11
    • 2012-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多