使用VBA对可见空白单元格进行计数?
当我在单元格中输入以下函数作为自定义项时:使用VBA对可见空白单元格进行计数?,vba,excel,Vba,Excel,当我在单元格中输入以下函数作为自定义项时: Function VisibleBlankCells(r As Range) As Long On Error Resume Next VisibleBlankCells = Intersect(r.SpecialCells(xlCellTypeVisible), r.SpecialCells(xlCellTypeBlanks)).Count On Error GoTo 0 End Function r.SpecialCell
Function VisibleBlankCells(r As Range) As Long
On Error Resume Next
VisibleBlankCells = Intersect(r.SpecialCells(xlCellTypeVisible), r.SpecialCells(xlCellTypeBlanks)).Count
On Error GoTo 0
End Function
r.SpecialCells(xlCellTypeBlanks)
将r
中的所有单元格计算为空,无论它们是否包含文本。这可能是什么原因,还有一种替代解决方案?首先要摆脱“错误时继续”的问题,然后重新开始“错误时继续”——您应该始终假设您的代码将失败,并对其进行相应的解释,简单地忽略错误只会使问题变得复杂
第二,不需要使用<代码>交叉> <代码> -只需直接识别可见的单元格,然后使用另一个<代码>特殊的Cys[/]代码>方法来识别空白子单元。
Function VisibleBlankCells(r As Range) As Long
VisibleBlankCells = r.SpecialCells(xlCellTypeVisible).SpecialCells(xlCellTypeBlanks).Count
End Function
用这个测试:
Sub test_code()
Dim r As Range: Set r = Selection
Debug.Print CountBlanks(r)
End Sub
Function CountBlanks(r As Range) As Long
CountBlanks = r.SpecialCells(xlCellTypeVisible).SpecialCells(xlCellTypeBlanks).Count
End Function
这种过滤机制在UDF中不起作用(有关这方面的信息,请参阅)。我建议在您的UDF中循环:
Public Function VisibleBlankCells(rng As Range) As Long
Dim i As Integer
Dim cell As Range
i = 0
For Each cell In rng
If cell.Rows.Hidden = False And _
cell.Columns.Hidden = False And _
cell.Value = "" Then
i = i + 1
End If
Next
VisibleBlankCells = i
End Function
但是,在更新和功能方面可能存在一些问题:
您是否已尝试删除“下一步恢复时出错时的<代码>(抖动)语句”以查看是否确实存在错误?您使用的Excel版本是什么?2010。。。更多单词blaOP正在使用Excel 2013。xlCellTypeBlanks在选择时返回“正确”的地址和计数。但是不正确,当我使用它作为自定义项并在r上执行它作为Range时,我只能对您的数据进行假设,我已经使用
选择和自定义项对此进行了测试,它在Excel 2010中运行良好…请参阅上面的编辑并尝试使用该代码。这对我来说很好我也这么做了。