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

下面的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 

如果您认为它将超过32767,则将“ Integer更改为“ Long

如果我要发送worksheet.cell到函数,它会检查整个工作表中的所有单元格,相当多很慢。 尽pipeExcel 2007+支持16384 * 1048576行,但只有实际使用的单元格才会加载到内存中。 没有必要通过其他170亿个单元来检查。 最接近我可以得到识别这些使用Worksheet.UsedRange来限制任意范围input。 尽pipe如此,在细胞分开的情况下,这并不完美。 例如,如果单元格A1和XFD1048576包含数据,则整个工作表将包含在UsedRange中。 有关如何限制范围到实际使用的单元格(上面的例子中只是两个单元格)的任何提示将不胜感激。

使用UsedRange我build立了一个function,我将分享以防其他人可以使用它的情况:

 Public Function CountIfFormula(ByRef rng As Range, Optional ByVal matchStr As String) As Long 'Counts the number of cells containing a formula and optionally a specific string (matchStr) in the formula itself. Dim i As Long Dim isect As Range 'Restricts the range to used cells (checks only cells in memory) Set isect = Application.Intersect(rng, rng.Parent.UsedRange) For Each cell In isect If cell.HasFormula Then If InStr(1, cell.Formula, matchStr) Then i = i + 1 End If Next CountIfFormula = i End Function 

使用function:

 Sub GetNrOfCells() Dim i As Long Dim ws As Worksheet For Each ws In ThisWorkbook.Worksheets i = i + CountIfFormula(ws.Cells, "=SUM(") Next 'i will now contain the number of cells using the SUM function End Sub 

最好的问候,并感谢您的答复。

Fossie