用0代替空

时间:2018-07-12 10:23:15

标签: 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

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

2 个答案:

答案 0 :(得分:6)

您不需要遍历所有单元格。让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的数据块,然后使用随机数发生器在其中打了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

答案 1 :(得分:2)

我从未使用过替代方法。我将使用cell = WorksheetFunction.Substitute(cell, "", "0")函数检查单元格是否为空。

所以你可以交换

If IsEmpty(cell) Then cell.value = 0

使用

Sub replace() Dim rng As Range, cell As Range Dim aantalrijen As Long With Application.ThisWorkbook.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 If IsEmpty(cell) Then cell.value = 0 Next End With End Sub

完整代码:

{{1}}