Home » excel » excel – Macro crashes after running. Anyway to make code/formula more efficient?

excel – Macro crashes after running. Anyway to make code/formula more efficient?

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have about 250,000 rows and the following code takes really long to process. Is there a way to shorten the formula or create custom functions so as to make it run quicker and more efficiently?

Sub test123()


Dim lastrow, lastrowAI As Long


lastrow = Cells(Rows.Count, "C").End(xlUp).Row
lastrowAI = Cells(Rows.Count, "AI").End(xlUp).Row


For i = lastrowAI + 1 To lastrow

Range("AI" & i).Formula = "=IF(F" & i & ">=EDATE(MAX($F$11:$F$1048576),-23),""Latest Months"",""Consol. Years"")"


Next


End Sub
How to&Answers:

Yes there is. Enter the formula in all cells in one go instead of doing that in a loop.

Untested

Sub test123()
    Dim lastrow, lastrowAI As Long
    Dim ws As Worksheet
    Dim sFormula As String

    '~~> Change this to the relevant worksheet
    Set ws = ThisWorkbook.Sheets("Sheet1")

    With ws
        lastrow = .Cells(.Rows.Count, "C").End(xlUp).Row
        lastrowAI = .Cells(.Rows.Count, "AI").End(xlUp).Row + 1

        sFormula = "=IF(F" & lastrowAI & _
                   ">=EDATE(MAX($F$11:$F$1048576),-23),""Latest Months"",""Consol. Years"")"

        .Range("AI" & lastrowAI & ":AI" & lastrow).Formula = sFormula
    End With
End Sub