在给定范围内哪些单元格为空

时间:2015-12-13 01:20:04

标签: excel vba excel-vba

我有一个给定范围的空格数。我想告诉用户哪些单元格是空的。这是功能:

Sub check()
'   Goal: check if there are any entry truth table cells for outputs
Dim outputsrange As range
Set outputsrange = range(inputnum + 1 & ":" & inputnum + outputnum)
If IsEmpty(outputsrange) Then
    MsgBox ("The following cells are empty:" & vbNewLine & emptycell)
Else
    Call makekmap
End If
End Sub

我把“emptycell”放在哪里?

编辑:新代码仍未运行,但具有正确的对象定义。

Sub check()
Dim outputsrange As range, emptycells As range
Set outputsrange = range(inputnum + 1 & ":" & cases)
Set emptycells = outputsrange.SpecialCells(xlCellTypeBlanks)
If Not emptycells Is Nothing Then
    MsgBox "The following cells are empty:" & vbNewLine & emptycells.Address
Else
    MsgBox ("No cells are empty")
End If
End Sub

2 个答案:

答案 0 :(得分:2)

检查带有 xlCellTypeBlanks 选项的Range.SpecialCells method是否报告空白单元格,如果存在则输出联合Range.Address property

Dim inputnum As Long, outputnum As Long
Dim outputsrange As Range, mtCells As Range
inputnum = 1: outputnum = 6
Set outputsrange = Range(inputnum + 1 & ":" & inputnum + outputnum)
On Error Resume Next
Set mtCells = outputsrange.SpecialCells(xlCellTypeBlanks)
On Error GoTo 0
If Not mtCells Is Nothing Then
    MsgBox "The following cells are empty:" & vbNewLine & _
           mtCells.Address(0, 0)
Else
    Call makekmap
End If

请注意,包含返回零长度字符串的公式的单元格(例如"")并非真正空白。

交替没有错误继续下一步

Dim inputnum As Long, outputnum As Long
Dim outputsrange As Range
inputnum = 1: outputnum = 6
Set outputsrange = Range(inputnum + 1 & ":" & inputnum + outputnum)
If CBool(Application.CountBlank(outputsrange)) Then
    MsgBox "The following cells are empty:" & vbNewLine & _
           outputsrange.SpecialCells(xlCellTypeBlanks).Address(0, 0)
Else
    Call makekmap
End If

你必须要小心,因为工作表的COUNTBLANK function会将包含零长度字符串的单元格计为空白,但是SpecialCells(xlCellTypeBlanks)则不会。可能,你可以 有一种情况,你进入MsgBox区域,但没有任何报告。

答案 1 :(得分:2)

避免错误的另一种方法:

Sub check()
  Dim outputsrange As Range, runner As Variant
  Set outputsrange = Range(inputnum + 1 & ":" & inputnum + outputnum).CurrentRegion
  For Each runner In outputsrange.Formula
    If Len(runner) = 0 Then
      MsgBox "The following cells are empty:" & vbNewLine & _
      outputsrange.SpecialCells(xlCellTypeBlanks).Address(0, 0)
      Exit Sub
    End If
  Next
  Call makekmap
End Sub

修改

从Jeeped那里得到答案以及Tim Williams的评论,你可以将它与我的解决方案合并到:

Sub check()
  Dim outputsrange As Range, runner As Variant
  Set outputsrange = Range(inputnum + 1 & ":" & inputnum + outputnum).CurrentRegion
  If Application.CountBlank(outputsrange) Then
    MsgBox "The following cells are empty:" & vbNewLine & _
      outputsrange.SpecialCells(xlCellTypeBlanks).Address(0, 0)
    Exit Sub
  End If
  Call makekmap
End Sub

应该是获得所需内容的最快方式,也不会因为outputsrange本身有效而在日志中弹出任何错误。