[英]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.