1

Is there any quicker method than using a for loop to find the first instance of a formula in a cell?

For Each dc In .Worksheets("testWS").Range(searchRange)
    If dc.hasFormula() = True Then
        formulaRow = Split(dc.Address, "$")(2)
        formula = dc.formula
        Exit For
    End If
Next
2
  • 4
    Range.SpecialCells(xlCellTypeFormulas)?
    – BigBen
    Feb 26, 2020 at 17:01
  • using a variant array of formulas would probably be a bit quicker if you're going to loop... arr = range(searchRange).formula as opposed to .value
    – Cyril
    Feb 26, 2020 at 17:01

2 Answers 2

8

No loop needed - use Range.SpecialCells. Include error handling since there may be no cells with formulas.

On Error Resume Next
Dim formulaRng As Range
Set formulaRng = .Worksheets("testWS").Range(searchRange).SpecialCells(xlCellTypeFormulas)
On Error GoTo 0

If Not formulaRng Is Nothing Then
    Debug.Print formulaRng.Cells(1).Row
    Debug.Print formulaRng.Cells(1).Formula
End If
0
-1
Function FindFirstFormulaRow(ByRef rng As Range) As Long

    Dim arrFormulas As Variant

        Set arrFormulas = rng.SpecialCells(xlCellTypeFormulas)    
        Set rng = arrFormulas

            If Not rng Is Nothing Then
                FindFirstFormulaRow = Split(rng.Cells(1).Address, "$")(2)
                Set rng = rng.Cells(1)
            End If
End Function`
1
  • Why the downvote? It returns the row of the first cell of the range you passed in that contains a formula without a loop. arrFormulas contains all the range SpecialCells and arrFormulas(1) is the first formula cell
    – LudieJ
    Mar 19, 2020 at 16:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.