繁体   English   中英

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

[英]VBA UDF gives different answer when called from Excel vs 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

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

如果我要将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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM