1

我目前正在计算股票投资回报率。我有大约 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 - 在列上它需要打印输出

4

2 回答 2

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

我引用的答案。

于 2013-03-16T13:24:56.630 回答
0

如果您不想更改当前代码,利用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
于 2013-03-16T21:57:53.467 回答