【问题标题】:Slower performance of calculation in Excel VBAExcel VBA 中的计算性能较慢
【发布时间】:2013-03-16 13:06:52
【问题描述】:

我目前正在计算股票投资回报率。我有大约 10 年的历史数据,而我构建函数的方式需要很长时间才能完成这项工作。例如,我有 11 列和 2872 行来计算每天的回报。

my Function
     Public Sub CalcROI(ByVal ColPick As Integer, ByVal ColPrint As Integer)

     Dim irow As Integer
     Dim iCol As Integer

     For irow = 4 To 2873
    'Calculating ROI
      Cells(irow + 1, ColPrint).Value = (Cells(irow + 1, ColPick).Value - Cells(irow, ColPick).Value) / Cells(irow, ColPick).Value
      Next irow

      End Sub

程序的实现是

 CalcROI ColPick:=4, ColPrint:=17

ColPick - 需要从哪里选择值进行计算

ColPrint - 在列上需要打印输出

【问题讨论】:

  • 您的问题没有问题!我想你想加快速度。您可以在计算中取出 +1 并将 For 参数更改为运行 5 到 2784,但为什么不将公式放入电子表格中?
  • 因为我想使用 VBA 菜单驱动程序动态执行操作...我基本上是在计算风险价值 - 历史方法和该表中的股票信息来自彭博终端...以上是 VaR 计算的一部分
  • 您可以通过在开头添加 Application.Screenupdating = false 来显着加快当前代码的运行速度。

标签: excel stock vba


【解决方案1】:

我不知道这是否可行,只是想测试我昨天在另一个问题上看到的东西。如果您对其进行测试,请在您的工作簿的副本中运行它,以防出现严重错误!

更新

我已经对其进行了测试(仅使用一列 > 0 的随机数)并且它确实有效。

Public Sub CalcROI(ByVal ColPick As Integer, ByVal ColPrint As Integer)
Dim rgPick As Range
Dim vaPick As Variant
Dim rgPrint As Range
Dim vaPrint As Variant
Dim Row As Integer

    Set rgPick = Range(Cells(4, ColPick), Cells(2873 + 1, ColPick))
    vaPick = rgPick.Value

    Set rgPrint = Range(Cells(4, ColPrint), Cells(2873 + 1, ColPrint))
    vaPrint = rgPrint.Value

    For Row = LBound(vaPick) To UBound(vaPick) - 1
        vaPrint(Row + 1, 1) = (vaPick(Row + 1, 1) - vaPick(Row, 1)) / vaPick(Row, 1)
    Next Row

    rgPrint = vaPrint

End Sub

我引用的Answer

【讨论】:

    【解决方案2】:

    如果您不想更改当前代码,使用 Application.ScreenUpdating 将有助于实现这一点(以及使您未来的几乎所有 Excel VBA 代码运行得更快)。


    Public Sub CalcROI(ByVal ColPick As Integer, ByVal ColPrint As Integer)
         'this stops Excel from updating the screen after every single iteration in your loop
         'in the future, this is an EASY way to speed up the majority of Excel macros
         Application.screenupdating = false  
         Dim irow As Integer
         Dim iCol As Integer
    
         For irow = 4 To 2873
        'Calculating ROI
          Cells(irow + 1, ColPrint).Value = (Cells(irow + 1, ColPick).Value - Cells(irow, ColPick).Value) / Cells(irow, ColPick).Value
          Next irow
          'this isn't strictly speaking necessary, but will help
          application.screenupdating = true
          End Sub
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-30
      • 1970-01-01
      • 2017-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-25
      • 1970-01-01
      相关资源
      最近更新 更多