我有Selection
,可以是任意随机范围,例如("A1:O10")
我需要确保此范围内所有空白的单元格的值都为NULL
。
我该怎么做?
For Each c In Selection.Cells
If Abs(c.Value) = "" Then c.Value = "NULL"
Next
答案 0 :(得分:5)
编辑作为答案,但在此处留下不的方式(基于simoco对SpecialCells和UsedRange的观察)
On Error Resume Next
Selection.SpecialCells(xlCellTypeBlanks).Value = "NULL"
On Error Goto 0
修正了SpecialCells“otchas:
假设单区选择:
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