excel - 空的替换为0

标签 excel vba substitution

我想检查 D 至 O 列中的所有单元格。如果单元格为空,请将其替换为硬零。

我有这个代码:

Sub replace()
Dim rng As Range, cell As Range
Dim aantalrijen As Long

    With Worksheets("Schaduwblad")
        aantalrijen = .Range("A1", .Range("A1").End(xlDown)).Cells.Count - 1
        Set rng = .Range(.Cells(2, "D"), .Cells(aantalrijen, "O"))

        For Each cell In rng
            cell = WorksheetFunction.Substitute(cell, "", "0")
        Next
    End With
End Sub

此代码在处理过程中挂起。唯一的选择是按 Esc 键结束例程。

最佳答案

您不需要循环遍历所有单元格。让 Excel 使用 .SpecialCells 查找空值:

On Error Resume Next
rng.SpecialCells(xlCellTypeBlanks, xlCellTypeConstants).Value = 0
On Error GoTo 0

如果没有找到空单元格,则需要错误陷阱。

<小时/>

所以你的整个日常工作可以被替换为:

Sub replace()

    On Error Resume Next

      With Worksheets("Schaduwblad")
            .Range(.Cells(2, "D"), .Cells(.Cells(.Rows.Count, 1).End(xlUp).Row, "O")) _
                .SpecialCells(xlCellTypeBlanks, xlCellTypeConstants).Value = 0
      End With

    On Error GoTo 0

End Sub
<小时/>

根据您在下面的评论,这里是相同代码的一个版本,但逐行工作。为了测试这一点,我构建了一个 227,000 x 15 的数据 block ,然后使用随机数生成器在其中打了 100,000 个孔,清空了这些单元格。然后我运行了以下代码,花了 33 秒来填补这 100,000 个漏洞。

Sub replace()

Dim rangesection As Range

    On Error Resume Next

      With Worksheets("Schaduwblad")
        For Each rangesection In .Range(.Cells(2, "D"), .Cells(.Cells(.Rows.Count, 1).End(xlUp).Row, "O")).Rows
            rangesection.SpecialCells(xlCellTypeBlanks, xlCellTypeConstants).Value = 0
        Next
      End With

    On Error GoTo 0

End Sub

关于excel - 空的替换为0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51303162/

相关文章:

EXCEL VBA : Format text after Point in each Cell

c++ - 如何使用 C 预处理器用环境变量进行替换

vba - 在多个 Excel 文件上运行相同的 Excel 宏

excel - 应该引用什么对象来使用 UsedRange 属性?

excel - VBA运行时错误 '9' : Subscript out of range; trying to activate another workbook

regex - Perl 条件替换

yaml - 将 Yaml 值替换为 yq 并用新值作为 bash 函数的输出,该函数接受当前值作为输入

php - 相同字符串的不同长度

string - 如何在字符串中找到引用的文本?

excel - 将点击事件添加到命令按钮