运行后宏崩溃。无论如何,使代码/公式更有效率?

时间:2014-01-08 09:25:17

标签: excel vba excel-vba

我有大约250,000行,以下代码需要很长时间才能处理。有没有办法缩短公式或创建自定义函数,以使其更快更有效地运行?

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

1 个答案:

答案 0 :(得分:3)

是的。一次性在所有单元格中输入公式,而不是在循环中进行。

<强>未测试

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