在大型數據集上執行優化任務時,我會不時收到溢出運行時錯誤6(通常在1小時或2小時後)。當我從它停止的位置重新啓動宏時,錯誤消失,即從發生錯誤的位置再次啓動宏。溢出錯誤是否與創建過多的使用後未被正確銷燬的對象有關?Excel VBA:來自太多未被破壞的對象的溢出錯誤?
下面是我的容器類的一個(簡化版本),它被銷燬(通過Set ... = Nothing)和重建(通過Set ... = New)成千上萬次。
'CG_data_point custom collection class
Public data_points As Collection
Private Sub Class_Initialize()
Set data_points = New Collection
End Sub
Public Sub AddDataPoint(mydate as date, price as double)
Dim new_data_point As CG_data_point
Set new_data_point = New CG_data_point
new_data_point.EnterData mydate, price
data_points.Add new_data_point
Set new_data_point = Nothing 'I assume this one could also be skipped
End Sub
Public Sub RMSE(X as double) as double
...
End Sub
Private Sub Class_Terminate()
Dim data_point As CG_data_point
For Each data_point In data_points 'destruct each data point individually
Set data_point = Nothing
Next data_point
Set data_points = Nothing
End Sub
'Main module
dim global_container as CG_data_container
sub do_optimizations()
Do
set global_container= new CG_data_container
.... do something with the data, have in call to global function RMSE_UDF as a cell formula for Solver
set global_container= nothing
While (...)
end sub
'worksheet function
function RMSE_UDF(X as double)
global_container.RMSE(X)
end function
容器變量global_container必須是全球因爲它必須從工作表UDF(RMSE_UDF)調用的對象;就我所知,工作表公式不能有一個對象作爲參數,如「= RMSE(MyContainer,...)」。使用Excel Solver進行均方根誤差(RMSE)的最小化。
這很有道理。感謝您向我指出這個錯誤。使用其他語言的指針和引用計數器時,有點混淆。但是,如果任何機構有另一個想法,爲什麼可能會有這個問題,我會很樂意在這裏。 – Steve06 2011-04-18 23:49:30
我對你提出的解決方案有一個額外的問題:是不是在析構函數中使用Set data_points = Nothing命令清空集合? – Steve06 2011-04-19 00:26:33
你真的碰到了印記,在用你的Class_Terminate替換我的循環後(包括刪除),即使連續運行了10個小時的宏,錯誤也沒有彈出!所以我推斷,正如我最初猜測的那樣,溢出錯誤(即運行時錯誤6)很可能源於未被破壞的對象。 – Steve06 2011-04-19 16:28:57