此代码始终返回单元格不为空。为什么是这样?我的范围不正确吗?此代码位于另一个工作表上的命令按钮中。我还打算使行号在for循环中执行,但需要在继续之前使此代码正常工作。请注意我有列地址,号码和信件。
任何帮助表示赞赏 - 谢谢 杰里
columnletterstart = "A"
columnletterend = "D"
Let therange = columnletterstart & "20" & ":" & columnletterend & "20"
Cells(6, 6) = therange
If IsEmpty(Worksheets("Vacation Schedule").Range(therange)) = False Then
'Cell A2 is not blank
MsgBox "Cell is not empty"
Else
'Cell A2 is blank
MsgBox "Cell is empty"
End If
答案 0 :(得分:2)
你正在传递IsEmpty
多区域范围(A20:D20),它将其解释为2D Variant数组,其中不为空,因为它是一个初始化的数组空变种。 IsEmpty
适用于不包含公式的单细胞范围。
IsEmpty和单个单元格的示例:
If IsEmpty(Worksheets("Example").Cells(1, 1).Value2) Then ...
如@SJR所述,要检查覆盖多个单元格的范围的空虚,您需要查看COUNTA
:
If Application.WorksheetFunction.CountA(Worksheets("Vacation Schedule").Range(therange)) > 0 Then
修改强>
一个反复出现的问题是您有时想要将包含零长度字符串的单元格视为空; Application.WorksheetFunction.CountA
计算此类单元格,无论它们是否包含常量(例如'
)或导致""
的公式。
在考虑范围的空白时,以下函数可选地跳过零长度字符串:
Public Function IsRangeEmpty(ByVal prngTest As Excel.Range, pbZeroLengthStringIsEmpty As Boolean) As Boolean
IsRangeEmpty = prngTest.Find("*", LookIn:=IIf(pbZeroLengthStringIsEmpty, xlValues, xlFormulas), LookAt:=xlPart, SearchDirection:=xlNext, MatchCase:=False, MatchByte:=False, SearchFormat:=False) Is Nothing
End Function
答案 1 :(得分:0)
说实话,本周我遇到了同样的问题。
由于IsEmpty
和CountA
没有返回正确的结果,我最终编写了自己的方法:
Function CheckRange(passedRange As range) As Boolean
Dim cell As range
Dim rangeCounter As Integer
rangeCounter = 0
For Each cell In passedRange
If cell.Value <> "" Then
rangeCounter = rangeCounter + 1
Exit For
End If
Next cell
If rangeCounter = 0 Then
CheckRange = True
Else
CheckRange = False
End If
End Function
这样称呼:
Dim columnletterstart As String
Dim columnletterend As String
Dim concatenateString As String
Dim testRange As range
columnletterstart = "A"
columnletterend = "D"
concatenateString = columnletterstart & "20" & ":" & columnletterend & "20"
Set testRange = range(concatenateString)
If CheckRange(testRange) Then
MsgBox "empty"
Else
MsgBox "not empty"
End If