VBA限制范围为前1000行

时间:2018-08-14 13:26:53

标签: excel range

我有以下VBA代码遍历excel电子表格的D列,如果单元格中的值为“ x”,则它将隐藏该行。运行时,它运行正常,但随后又滞后了一段时间,我认为这是因为它正在搜索D列中的每个单元格。我已经很累了将范围设置为“ D1:D1000”,但是该范围没有运行。有什么方法可以将此代码设置为仅检查前1000个单元格吗?

Sub Button1_Click()

Dim sh As Worksheet
Dim rw As Range
Dim RowCount As Integer

RowCount = 0

Set sh = ActiveSheet
For Each rw In sh.Rows

  If sh.Cells(rw.row, 4).Value = "x" Then
    sh.Cells(rw.row, 4).EntireRow.Hidden = True
    RowCount = RowCount + 1
  End If
Next rw

End Sub

2 个答案:

答案 0 :(得分:2)

使用自动筛选方法的替代方法:

Sub Button1_Click()

    Dim ws As Worksheet

    Set ws = ActiveWorkbook.ActiveSheet
    With ws.Range("D1", ws.Cells(ws.Rows.Count, "D").End(xlUp))
        'Unhide all rows
        If .Parent.AutoFilterMode = True Then .Parent.AutoFilterMode = False
        .EntireRow.Hidden = False

        'Filter out to hide desired rows
        .AutoFilter 1, "<>x"
    End With

End Sub

答案 1 :(得分:1)

您可以做一些事情来延长运行时间

  1. 关闭屏幕更新
  2. 如果表格上有很多公式,请关闭“自动计算”
  3. 您可以遍历范围并将目标行添加到Union中,而不是逐行隐藏每一行,然后在完成循环后同时隐藏Union行。

Sub Button1_Click()

Dim sh As Worksheet: Set sh = ActiveSheet
Dim LoopRange As Range: Set LoopRange = sh.Range("D1:D1000")
Dim CurrentRow As Range

For Each CurrentRow In LoopRange
    If CurrentRow = "x" Then
        CurrentRow.EntireRow.Hidden = True
    End If
Next CurrentRow

End Sub