VBA - 如何将范围内的空单元格设置为零

VBA - how to set empty cells in a range to zero

我还是 Visual Basic 的新手,我想创建一个宏,基本上用零值(整数)填充空单元格,同时将现有单元格保留在范围内(如果不为空) .我的代码目前是这样的:

 Sub FillEmptyCellsWithZeros()

'this should fill empty cells with a 0 value for the range selected



 Dim cell As Object
    Dim y As Integer

    y = 0
    For Each cell In Selection
      If y = Empty Then 
      Selection.Value = 0 
      ElseIf y <> Empty Then 
      Selection.Value = ActiveCell.Value 
      End If 
    Next cell

End Sub

我知道很可能我的循环在这段代码中没有做任何事情,但我似乎无法得到结果,而这段代码是我得到的最接近的结果。

如有任何帮助,我们将不胜感激。

谢谢

你有点想多了:

 Sub FillEmptyCellsWithZeros()

'this should fill empty cells with a 0 value for the range selected



 Dim cell As Object
    Dim y As Integer

    y = 0
    For Each cell In Selection
      If cell = "" Then
        cell = y
      End If
    Next cell

End Sub

不要从 Scott 的回答中拿走任何东西,但如果您对 non-looping 回答感兴趣,您可以尝试类似的方法:

Selection.SpecialCells(xlCellTypeBlanks).Value = 0

如果您有大量不连续范围的大量选择,这可能会导致问题,但它应该非常可靠。

此外,如果您的公式 returns 为空白(例如):

=IF(E16="","")

它不会将那些视为空白(这意味着它们在 运行 代码之后仍然 "appear" 空白),因此您的里程数可能非常多。