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

时间:2013-01-03 15:06:31

标签: 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

2 个答案:

答案 0 :(得分:3)

这是不可能的。以下链接包含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

答案 1 :(得分:0)

如果我要将workheet.cells发送到该函数,它将检查整个工作表中的所有单元格,非常多且非常慢。虽然Excel 2007+支持16384 * 1048576行,但只有实际使用过的单元格才会加载到内存中。没有必要通过所有其他170亿个细胞来检查。我最接近识别这些是使用Worksheet.UsedRange来限制任意范围输入。但是,如果使用相距很远的细胞,那么它并不完美。例如。如果单元格A1和XFD1048576包含数据,则整个工作表将包含在UsedRange中。关于如何将范围限制为实际使用的单元格的任何提示(上例中只有两个单元格)将不胜感激。

利用UsedRange我建立了一个我将分享的功能,以防其他任何人可以使用它:

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

使用该功能:

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