我需要优化我的代码,因此运行速度更快。它只有12000个计算。我的工作表中有大约6 000行,我需要计算一列中的回报率和另一列中的对数回报率。
问题在于,当我使用Excel公式进行这些计数时,每列需要2-3秒,因此6 000行的返回率在2秒内计算,相同的以秒为单位的对数率柱。 但我的代码需要60秒才能运行。 这怎么可能呢?我确信VBA计算会比这快得多。
Sub Normal_Return_Rate()
Dim ws As Worksheet
Dim current_price As Single
Dim previous_price As Single
Dim a_cell As Range
Dim b_cell As Range
Dim vba_cell As Range
Dim row As Long
Dim b_col As Integer
Dim vba_col As Integer
Dim last_row As Long
Dim start As Double
Dim finish As Double
Dim total_time As Double
Application.ScreenUpdating = False
start = Timer ' remember time when macro starts.
Set ws = Workbooks("lista_spolek_gpw.xlsm").Worksheets("MBank_Statsy")
last_row = ws.Cells(Rows.Count, 1).End(xlUp).row
row = 3
Set a_cell = ws.Range("A1:ZZ1").Find(What:="LOW", LookIn:=xlValues, LookAt:=xlWhole, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
Set b_cell = ws.Range("A1:ZZ1").Find(What:="CLOSE", LookIn:=xlValues, LookAt:=xlWhole, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
Set vba_cell = ws.Range("A1:ZZ1").Find(What:="VBA code" & Chr(10) & "result", LookIn:=xlValues, LookAt:=xlWhole, SearchDirection:=xlNext, _
MatchCase:=True, SearchFormat:=False)
b_col = b_cell.Column
vba_col = vba_cell.Column
ws.Cells(row, b_col).Activate
With ws.Range("M3:N" & last_row)
' previous version: ws.Range("M2:N" & Rows.Count)
.HorizontalAlignment = xlGeneral
.VerticalAlignment = xlCenter
.WrapText = False
.NumberFormat = "00.00%"
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
.ColumnWidth = 13
End With
With ws
Do While Cells(row, b_col) <> ""
current_price = ActiveCell.Value
previous_price = ActiveCell.Offset(-1, 0).Value
ws.Cells(row, vba_col) = Round(current_price / previous_price - 1, 4)
ws.Cells(row, 14) = Log(current_price / previous_price)
row = row + 1
ws.Cells(row, b_col).Activate
Loop
End With
finish = Timer
total_time = Round(finish - start, 3) ' Calculate total time.
MsgBox "This code ran successfully in " & total_time & " seconds", vbInformation
Application.ScreenUpdating = True
End Sub
非常感谢任何使这段代码运行得更快的建议。我只是VBA的初学者。
这是表格的样子 - 股票报价单。 计算使用的是&#34; CLOSE&#34;列。