【问题标题】:VBA processing speed of macro宏的VBA处理速度
【发布时间】:2017-06-22 14:45:47
【问题描述】:

我有这个代码:

Option Explicit

Private Sub Label1_Click()

Application.ScreenUpdating = False

Dim ws As Worksheet
Dim rng1 As Range

Set ws = ActiveWorkbook.ActiveSheet

ws.Cells(3, 3).Activate

'runs a loop for active range - tests if the product on current line matched the line above and then returns a variance

Do While ActiveCell <> vbNullString
    ActiveCell.Offset(0, 11).Interior.ColorIndex = 19

    'formatting & formulation
    With ActiveCell.Offset(0, 12)
        .FormulaArray = "=IFERROR(SUM(IF(C" & ActiveCell.Row & "=ItemCode,ValueAmt))/SUM(IF(C" & ActiveCell.Row & "=ItemCode,KGs)),I" & ActiveCell.Row & ")"
        .Interior.ColorIndex = 19
        .NumberFormat = "0.0000"
        .Font.ColorIndex = xlAutomatic
        .Font.TintAndShade = 0
        .Font.Bold = True
    End With


    'clearing all but last row for each product
'   If ActiveCell = ActiveCell.Offset(1, 0) Then
'   ActiveCell.Offset(0, 12).ClearContents
'   End If

    ActiveCell.Offset(1, 0).Activate

    'looping data
        If ActiveCell.Offset(-1, 0) = ActiveCell Then

            If ActiveCell.Offset(-1, 7) = 0 Then
            ActiveCell.Offset(0, 11).Value = ActiveCell.Offset(0, 7).Value
            Else
            ActiveCell.Offset(0, 11).Value = ((ActiveCell.Offset(0, 7).Value - ActiveCell.Offset(-1, 7).Value) / ActiveCell.Offset(-1, 7).Value)
            End If

        End If

Loop

With Columns(ws.UsedRange.Columns.Count)
    .NumberFormat = "0.00%"
End With

With UsedRange
    .Columns.AutoFit
    .Rows.AutoFit
End With

'MsgBox "run macro"
Application.ScreenUpdating = True

End Sub

按我的意愿工作,它获取成本信息并逐项生成差异(如果项目代码匹配)和加权平均成本。

我的问题是,即使屏幕更新 = false,处理速度也很慢。我知道这与 ACTIVECELL OFFSET 有关,因为我知道这是执行循环的减慢方式。我遇到的问题是,因为我的公式是一个数组公式,我必须使用 .FormulaArray 属性,我认为这是减慢它的原因。

有没有人知道一种更好的方法来重新构造此代码以实现相同/相似的结果?我也许可以尝试一个 Do While 循环。

【问题讨论】:

  • 我投票决定将此问题作为离题结束,因为随着代码的工作和 OP 正在寻找使其更快的指导,它更适合codereview.stackexchange.com 请在此处发布此问题为这个论坛太宽泛了。
  • 谢谢。我不知道那个网站存在。将来会知道

标签: arrays vba loops for-loop


【解决方案1】:

除了 ScreenUpdating,您还可以在运行代码之前尝试将 Calculation 设置为手动。

Application.Calculation = xlCalculationManual

然后一旦循环完成,再次打开它:

Calculate
Application.Calculation = xlAutomatic

【讨论】:

  • 效果很好,谢谢!只花了几秒钟。这个函数有什么作用? (我以前见过但没用过)
  • 通常,当单元格或单元格区域的先例发生更改时,Excel 会自动重新计算该单元格或单元格区域。因此,您只需要在此期间关闭,以免工作簿过于频繁地重新计算。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-30
  • 1970-01-01
  • 2023-01-18
  • 1970-01-01
  • 2023-03-29
  • 1970-01-01
相关资源
最近更新 更多