Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用VBA对可见空白单元格进行计数?_Vba_Excel - Fatal编程技术网

使用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 
但是,在更新和功能方面可能存在一些问题:

  • UDF的值仅在编辑引用范围或调用其他UDF后更新。因此,如果在该范围内隐藏列或行,则不会产生即时效果
  • 在子程序中执行代码时,可见单元格(也)表示工作表中尚未使用的单元格“不可见”。但是,在我的解决方案中,不包含在隐藏行/列中的所有单元格都被视为可见
    您是否已尝试删除“下一步恢复时出错时的<代码>(抖动)语句”以查看是否确实存在错误?您使用的Excel版本是什么?2010。。。更多单词blaOP正在使用Excel 2013。xlCellTypeBlanks在选择时返回“正确”的地址和计数。但是不正确,当我使用它作为自定义项并在r上执行它作为Range时,我只能对您的数据进行假设,我已经使用
    选择和自定义项对此进行了测试,它在Excel 2010中运行良好…请参阅上面的编辑并尝试使用该代码。这对我来说很好我也这么做了。