excel - 从 Excel 与 VBA 调用时,VBA UDF 给出不同的答案

标签 excel vba

以下 VBA 函数计算给定范围内包含公式的单元格数量。从 VBA 子程序调用时它可以正常工作。从 Excel 调用时,它返回区域中的单元格总数。

来自 Excel 的调用是 =CountFormulas(A1:C7),即使该范围内只有两个包含公式的单元格,它也会返回 21。

是什么导致了这种差异?

Public Function CountFormulas(ByRef rng As Range) As Long
    CountFormulas = rng.SpecialCells(xlCellTypeFormulas).Count
End Function

Public Sub CountFormulasFromSub()
    Dim rng As Range
    Dim res As Integer
    Set rng = Sheet1.Range("a1:c7")
    res = CountFormulas(rng)
End Sub

最佳答案

这是不可能的。以下链接包含在 UDF 中不起作用的内容。
在这里 - http://support.microsoft.com/kb/170787

编辑:手动计数方式是有效的。

Public Function CountFormulas(rng As Range) As Integer
Dim i As Integer
Dim cell As Range

For Each cell In rng
    If cell.HasFormula Then
        i = i + 1
    End If
Next

CountFormulas = i
End Function

如果您认为Integer会超过32767,请将其更改为Long

关于excel - 从 Excel 与 VBA 调用时,VBA UDF 给出不同的答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14141513/

相关文章:

vba - 工作簿未通过作为参数传递在 Excel 中激活

excel - 在 Excel VBA 中初始化数组 - 出现错误

EXCEL VBA 检查条目是否为空 'space'

vba - 创建加载项以在 powerpoint 中添加便签 (VBA)

excel - 将新版本从 Google Drive 推送给用户 (VBA)

vba - 无法点击某些点来抓取信息

excel - 索引匹配匹配查询 Excel 2013

excel - 系统错误 &H8000FFF (-247418113)。灾难性故障

sql - 在值不为空的地方插入

VBA 回文函数