首页 > 解决方案 > 直到循环执行缓慢 - 偏移和选择的替代方案?

问题描述

代码循环遍历相当大的数据(1000 行乘 20 列)并删除单元格中没有错误但当前需要 20 分钟执行的行。寻找一种通过消除代码中对偏移和选择的需要来加速该过程的方法。

我曾尝试在代码前后关闭/打开自动计算,但这并没有明显影响运行时。屏幕更新已关闭。

Range("A6").Select
Do Until IsEmpty(ActiveCell)
    If IsError(ActiveCell) Then
        ActiveCell.Offset(1, 0).Select
    Else
        ActiveCell.EntireRow.Delete
    End If
Loop

保留区域 A 中的单元格为 N/A (IsError) 的行。按预期运行,但需要整整 20 分钟才能运行。

任何帮助表示赞赏。

标签: excelvba

解决方案


SpecialCells 可以快速查找所有返回布尔值、数字或文本的公式,同时排除错误。

dim rng as range

with worksheets("sheet1")
    with .range(.cells(6, "A"), .cells(.rows.count, "A").end(xlup))
        on error resume next
        set rng = .specialcells(xlCellTypeFormulas, xlLogical+xlNumbers+xlTextValues)
        on error goto -1
        if not rng is nothing then
            rng.entirerow.delete
        end if
    end with
end with

推荐阅读