我想检查列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结束例行程序。
我从来没有使用替代方法..我会通过IsEmpty()
函数检查单元格是否为空来完成此操作。
所以你可以互换
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
您不需要遍历所有单元格。让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