如何将选区中的所有空单元格转换为NULL值?

And*_*lev 1 excel vba excel-vba

我有一个Selection可以是任何随机范围,例如("A1:O10")

我需要确保此范围内的所有单元格都是空白的NULL.

我怎样才能做到这一点 ?

For Each c In Selection.Cells
        If Abs(c.Value) = "" Then c.Value = "NULL"
Next
Run Code Online (Sandbox Code Playgroud)

Tim*_*ams 5

编辑:被提议作为答案,但在此处留下如何这样做(基于simoco对SpecialCells和UsedRange的观察)

On Error Resume Next
Selection.SpecialCells(xlCellTypeBlanks).Value = "NULL"
On Error Goto 0
Run Code Online (Sandbox Code Playgroud)

固定为SpecialCells"otchas:

  • SpecialCells仅适用于工作表的UsedRange(即使您选择了该范围之外的单元格)
  • SpecialCells不适用于单格选择:在这种情况下,它会自动扩展为整页

假设单区选择:

With Selection
    With .Cells(.Cells.Count)
        If Not .HasFormula And Len(.Value) = 0 Then
            .Value = "NULL"
        End If
    End With
    If .Cells.Count = 1 Then Exit Sub  
    On Error Resume Next
    .SpecialCells(xlCellTypeBlanks).Value = "NULL"
    On Error GoTo 0
End With
Run Code Online (Sandbox Code Playgroud)

来自Siddharth Rout:另一种不使用循环的方法

Sub Sample()
    With ActiveSheet
        '~~> How like is that the bottom right cell is filled????
        '~~> Excel 2007+ - XFD1048576
        '~~> Excel 2003 - IV65536
        .Cells(.Rows.Count, .Columns.Count) = "A"

        If Selection.Cells.Count < 2 Then
            If Selection.Value = "" Then Selection.Value = "NULL"
        Else
            On Error Resume Next
            Selection.SpecialCells(xlCellTypeBlanks).Value = "NULL"
            On Error GoTo 0
        End If
        .Cells(.Rows.Count, .Columns.Count).ClearContents
    End With
End Sub
Run Code Online (Sandbox Code Playgroud)