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

时间:2014-02-13 19:31:44

标签: excel vba excel-vba

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

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

我该怎么做?

For Each c In Selection.Cells
        If Abs(c.Value) = "" Then c.Value = "NULL"
Next

2 个答案:

答案 0 :(得分:5)

建议将

编辑作为答案,但在此处留下的方式(基于simoco对SpecialCells和UsedRange的观察)

On Error Resume Next
Selection.SpecialCells(xlCellTypeBlanks).Value = "NULL"
On Error Goto 0

修正了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

来自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

答案 1 :(得分:3)

这应该可以解决问题

Sub BlankToNull()
    For Each cell In Selection
        If Not IsError(cell.Value) Then
            If cell.Value = vbNullString Then cell.Value = "NULL"
        End If
    Next cell
End Sub