IF为空退出子代码

我试图检查,如果单元格为空或空,它会显示一条消息,并退出子。 这是我的代码:

With Worksheets(1).[D3:D4, D6:D14] If WorksheetFunction.CountA(.Cells) = 0 Then MsgBox "Nothing to generate" & vbNewLine & _ "Set parameters and click generate." Exit Sub End If End With 

但是只有当整个[D3:D4, D6:D14]都是空的[D3:D4, D6:D14]代码才会起作用。 我希望它退出子即使只有一个单元格是空的。 所有单元格都需要有内容才能继续。 请帮忙。

您也可以使用SpecialCells

 Sub Check() Dim rng1 As Range On Error Resume Next With Worksheets(1).[D3:D4, D6:D14] Set rng1 = .SpecialCells(xlBlanks) If Not rng1 Is Nothing Then MsgBox "Nothing to generate" & vbNewLine & _ "Set parameters and click generate." Exit Sub End If End With End Sub 

后续问题

 Sub Check2() Dim rng1 As Range Dim rng2 As Range With Worksheets(1) Set rng1 = .Range(.[D3:D4], .[D6:D14]) End With On Error Resume Next Set rng2 = rng1.SpecialCells(xlBlanks) On Error GoTo 0 If Not rng1 Is Nothing Then MsgBox rng1.Cells.Count - rng2.Cells.Count & " were used" Else MsgBox "all cells used" End If End Sub 

您需要在范围内进行search,请尝试下面的代码:

 Sub CheckEmptyCellsinRange() Dim Rng As Range Dim cell As Range Set Rng = Worksheets(1).[D3:D4, D6:D14] For Each cell In Rng If IsEmpty(cell) Or IsNull(cell) Then MsgBox "Nothing to generate" & vbNewLine & _ "Set parameters and click generate." Exit Sub End If Next cell End Sub