coolactuary
New Member
- Joined
- Apr 17, 2016
- Messages
- 5
The examples I've checks, including from Excel MVPs have used Subs rather than Functions. I can get a Sub to work and I can get a Function to debug.print the right result, but when I call the function from a sheet I get the full UsedRange count, rather than the function count - see code below. Apologies if I'm being naive:
Code:
Function HowManyFormulasFixedSheet()
' Called from Sheet2, this *incorrectly* returns 6 formulas i.e. the full used range on Sheet1
CountFormulas = Sheets("Sheet1").UsedRange.SpecialCells(xlCellTypeFormulas).Count
Debug.Print "HowManyFormulasFixedSheet count: " & CountFormulas
HowManyFormulasFixedSheet = CountFormulas
End Function
Sub HowManyFormulasFixedSheetSub()
' This *correctly* prints formula count of 1.
CountFormulas = Sheets("Sheet1").UsedRange.SpecialCells(xlCellTypeFormulas).Count
Debug.Print "HowManyFormulasFixedSheetSub count: " & CountFormulas
End Sub
Function HowManyFormulasFixedSheetALT()
' This correctly returns 1 formula
CountFormulas = 0
For Each cell In Sheets("Sheet1").UsedRange.Cells
CountFormulas = CountFormulas + Abs(cell.HasFormula)
Next cell
Debug.Print "HowManyFormulasFixedSheetALT count: " & CountFormulas
HowManyFormulasFixedSheetALT = CountFormulas
End Function