我有一个程序可以执行555,179,505,439次循环,以便在我的分析中使用。分析的目的是找到最佳的体积比率,以确定在特定日期的体积大于/小于特定天数(2至200天)的体积平均值之后,股票是否会增加/减少价格平均日)。我想知道是否有更快或更简单的方法来使用不同的代码获得结果?我附上了excel文件。代码将需要2。21年才能运行。 Excel File
Private Sub Worksheet_Deactivate()
Dim StartTime As Double
Dim MinutesElapsed As String
StartTime = Timer
Dim i As Long
Dim j As Long
Dim k As Long
Dim Total_Rows_Compiled As Long
Total_Rows_Compiled = Worksheets("Compiled").Range("A" & Rows.Count).End(xlUp).Row
ReDim Date_Initial(2 To Total_Rows_Compiled) As Date
ReDim Date_Range(2 To Total_Rows_Compiled) As Date
ReDim Stock_Initial(2 To Total_Rows_Compiled) As String
ReDim Stock_Range(2 To Total_Rows_Compiled) As String
Worksheets("Compiled").Range("A2:B" & Total_Rows_Compiled).Copy _
Destination:=Worksheets("Volume Analysis").Range("A2:B" & Total_Rows_Compiled)
For i = 2 To Total_Rows_Compiled
For j = 2 To Total_Rows_Compiled
For k = 2 To 200
If Worksheets("Compiled").Cells(i, 2) - Worksheets("Compiled").Cells(j, 2) >= -k And Worksheets("Compiled").Cells(i, 2) - Worksheets("Compiled").Cells(j, 2) < 0 And Worksheets("Compiled").Cells(i, 1) = Worksheets("Compiled").Cells(j, 1) Then
Worksheets("Volume Analysis").Cells(i, k + 1) = (Worksheets("Compiled").Cells(i, 7) / (Worksheets("Volume Analysis").Cells(i, k + 1) + Worksheets("Compiled").Cells(i, 7)))*100
End If
Next k
Next j
Next i
MinutesElapsed = Format((Timer - StartTime) / 86400, "hh:mm:ss")
MsgBox "This code ran successfully in " & MinutesElapsed & " minutes", vbInformation
End Sub
答案 0 :(得分:1)
将范围读入数组进行计算应加快速度,因为对单元格的读/写操作很慢。这样我们将其减少到一次读取和一次写入操作。访问阵列要快得多,但这不能做任何神奇的事情。这些计算量仍然需要时间,但也许你可以把它减少到几天而不是几年。
'read into array
Dim Compiled() As Variant
Compiled = Worksheets("Compiled").Range("A1", "H" & Total_Rows_Compiled).Value
Dim Analysis() As Variant
Analysis = Worksheets("Volume Analysis").Range("A1", "GT" & Total_Rows_Compiled).Value
For i = 2 To Total_Rows_Compiled
For j = 2 To Total_Rows_Compiled
For k = 2 To 200
If Compiled(i, 2) - Compiled(j, 2) >= -k And Compiled(i, 2) - Compiled(j, 2) < 0 And Compiled(i, 1) = Compiled(j, 1) Then
Analysis(i, k + 1) = Analysis(i, k + 1) + Compiled(i, 7)
End If
DoEvents 'don't let Excel unresponsive
Next k
Next j
Next i
'write back
Worksheets("Volume Analysis").Range("A1", "GT" & Total_Rows_Compiled).Value = Analysis
如果这种改进不够,你应该考虑Excel是否是进行这种计算的正确工具(即使它是简单的数学运算,也是很多数学运算)。 Excel VBA不能多线程,因此您无法使用CPU的全部功能。使用线程优化的数学工具可以更快地从Excel文件中读取数据(例如Matlab)。
答案 1 :(得分:0)
PEH的阵列方法是可行的方法。
此外,我认为如果您只想查看每个股票,然后对股票和日期数据进行排序。然后你应该能够消除或大大减少编译行的第二个循环。