我想检查 Excel 中的范围是否为空。
如何用 VBA 代码编写:
If Range("A38":"P38") is empty
从我得到的评论中找到了解决方案。
Sub TestIsEmpty()
If WorksheetFunction.CountA(Range("A38:P38")) = 0 Then
MsgBox "Empty"
Else
MsgBox "Not Empty"
End If
End Sub
如果您发现自己处于无法使用的情况,CountA
那么首先将您的范围存储为数组并循环数组数据比循环范围/单元格数据要快得多。
Function IsRangeEmpty(ByVal rng As Range) As Boolean
'Converts a range to an array and returns true if a value is found in said array
Dim area As Range
For Each area In rng.Areas
If area.Cells.Count > 1 Then
'save range as array
Dim arr As Variant
arr = area.value
'loop through array
Dim cel As Variant
For Each cel In arr
'if cell is not empty then
If Len(Trim(cel)) > 0 Then
IsRangeEmpty = False
Exit Function
End If
Next cel
Else 'cannot loop on array with one value
'if cell is not empty then
If Len(Trim(area.Value2)) > 0 Then
IsRangeEmpty = False
Exit Function
End If
End If
Next area
IsRangeEmpty = True
End Function
如何使用它的示例:
Sub Test()
Debug.Print IsRangeEmpty(Range("A38:P38"))
End Sub
如果Range("A38:P38")
为空,则True
在即时窗口中打印;否则它会打印False
。
如果变量未初始化或显式设置为 Empty,则 IsEmpty 返回 True;否则,它返回 False。如果表达式包含多个变量,则始终返回 False。IsEmpty 仅返回对变体有意义的信息。(https://msdn.microsoft.com/en-us/library/office/gg264227.aspx)。因此,您必须分别检查范围内的每个单元格:
Dim thisColumn as Byte, thisRow as Byte
For thisColumn = 1 To 5
For ThisRow = 1 To 6
If IsEmpty(Cells(thisRow, thisColumn)) = False Then
GoTo RangeIsNotEmpty
End If
Next thisRow
Next thisColumn
...........
RangeIsNotEmpty:
当然,这里的代码比使用计数非空单元格的 CountA 函数的解决方案要多,但是如果找到至少一个非空单元格,GoTo 可以中断循环,并且可以更快地执行代码,特别是在范围很大并且您需要检测这种情况时。此外,与不是 VBA 函数的 Excel CountA 函数相比,这段代码对我来说更容易理解它在做什么。
Dim M As Range
Set M = Selection
If application.CountIf(M, "<>0") < 2 Then
MsgBox "Nothing selected, please select first BOM or Next BOM"
Else
'Your code here
End If
根据我刚刚了解到的经验,您可以这样做:
If Selection.Rows.Count < 2
Then End If`
稍后提供澄清(现在我正在工作)
Dim cel As Range, hasNoData As Boolean
hasNoData = True
For Each cel In Selection
hasNoData = hasNoData And IsEmpty(cel)
Next
True
如果没有单元格Selection
包含任何数据,这将返回。对于特定范围,只需 RANGE(...)
替换Selection
.
另一种可能的解决方案。计算空单元格并从单元格总数中减去该值
Sub Emptys()
Dim r As range
Dim totalCells As Integer
'My range To check'
Set r = ActiveSheet.range("A1:B5")
'Check for filled cells'
totalCells = r.Count- WorksheetFunction.CountBlank(r)
If totalCells = 0 Then
MsgBox "Range is empty"
Else
MsgBox "Range is not empty"
End If
End Sub
@TomM's
这只是对答案的一点补充/一个简单的功能来检查您的选择的单元格是否为空
Public Function CheckIfSelectionIsEmpty() As Boolean
Dim emptySelection As Boolean:emptySelection=True
Dim cell As Range
For Each cell In Selection
emptySelection = emptySelection And isEmpty(cell)
If emptySelection = False Then
Exit For
End If
Next
CheckIfSelectionIsEmpty = emptySelection
End Function
恕我直言,这条单行效果更好:
Application.Evaluate("SUMPRODUCT(--(E10:E14<>""""))=0")
在这种情况下,它评估范围 E10:E14 是否为空。