我想检查某个范围是否为空。因此我写了以下代码
Sub end_calculation1()
If WorksheetFunction.CountA(Range("D22:D27")) < 6 Then
MsgBox "Please fill in all the answers in range D22:D27"
End If
End Sub
这有效,但实际上我想检查两个范围。所以不仅D22:D27而且D29:D30。
关于如何让这个工作的任何想法?
答案 0 :(得分:1)
如果您要检查的范围太多,则可以添加更多IF
语句:
Public Sub end_calculation1()
If WorksheetFunction.CountA(Range("D22:D27")) < 6 Then
MsgBox "Please fill in all the answers in range D22:D27"
ElseIf WorksheetFunction.CountA(Range("E22:E27")) < 6 Then
MsgBox "Please fill in all the answers in range E22:E27"
End If
End Sub
对于多个范围,您可以使用过程循环遍历范围并调用函数来检查每个范围:
Public Sub end_calculation_update()
Dim rngs As Variant, i As Byte
rngs = Array("D22:D27", "E22:E27", "F22:F27")
For i = 0 To UBound(rngs)
If (emptyRange(CStr(rngs(i)))) Then
MsgBox "Please fill in all the answers in range " & rngs(i)
Exit Sub
End If
Next i
End Sub
Private Function emptyRange(rngAddress As String) As Boolean
emptyRange = WorksheetFunction.CountA(Range(rngAddress)) < 6
End Function
更新以回应评论
您可以在一行中检查所有范围:
Public Sub end_calculation_revised()
Dim rng As Range
Set rng = Range("D22:D27,D29:E30")
If (WorksheetFunction.CountA(rng) < rng.Cells.Count) Then
MsgBox "Please fill in all the answers in range " & rng.Address
End If
End Sub
答案 1 :(得分:1)
细胞D28是否总是满的,或者总是空的?
If WorksheetFunction.CountA(Range("D22:D30")) < 9 Then
MsgBox "Please fill in all the answers in range D22:D27 and D:28:D30"
End If
如果您不想在检测中包含单元格D28,那么在第一个之后只需要另一个If语句。
Sub end_calculation1()
If WorksheetFunction.CountA(Range("D22:D27")) < 6 Then
MsgBox "Please fill in all the answers in range D22:D27"
Exit Sub
End If
If WorksheetFunction.CountA(Range("D28:D30")) < 6 Then
MsgBox "Please fill in all the answers in range D28:D30"
End If
End Sub
Exit Sub用于阻止用户收到2条错误消息。
如果你想进一步发展,你可以保持一个&#34;错误字符串&#34;将错误消息添加到字符串并检测字符串在If语句末尾是否为空的位置。通过这种方式,您可以一次性捕获所有错误,并向用户显示尚未完成的单元格列表。