gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 11:21:39 28 4
gpt4 key购买 nike

以下 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com