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)
编辑:被提议作为答案,但在此处留下如何不这样做(基于simoco对SpecialCells和UsedRange的观察)
On Error Resume Next
Selection.SpecialCells(xlCellTypeBlanks).Value = "NULL"
On Error Goto 0
Run Code Online (Sandbox Code Playgroud)
固定为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
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)