2017-07-16 75 views
0

我不喜歡在類似的論壇中提問,因爲我相信每個問題都在我之前問過,所以我只是使用搜索。但現在我覺得自己有點愚蠢,因爲這是我第一次沒有找到任何答案。VBA:將對象添加到集合中會增加內存使用量

我有一個基於一段代碼,一個簡單的問題:

Dim demo_1, demo_2 As Variant 'declare the variables 
Dim DataCollection As Collection 'declare the collection 
Set DataCollection = New Collection 'define the collection 
demo_1 = import_demo(1, nb_var) 'load first dataset (+250 mb of memory) 
demo_2 = import_demo(2, nb_var) 'load second dataset (+250 mb of memory) 

所以,在總,我的程序使用的內存500 MB。現在我想填寫我的收藏與此對象的引用:

DataCollection.Add demo_1 'adding reference to a collection (+250 mb of memory Why??) 
DataCollection.Add demo_2 'adding reference to a collection (+250 mb of memory Why??) 

所以我重複我的問題:「爲什麼----?」抱歉。

如果向集合中添加對象會增加VBA中的內存使用量,因爲我顯然不克隆?

回答

2

看起來你的import_demo(1, nb_var)函數返回一個數組。將數組添加到集合中會添加數組的副本。如果你的函數返回一個250MB的數組,那麼該數組的每一個副本將增加另一個250MB。

看到這個簡單的例子:

Sub test() 

    Dim coll As Collection 
    Set coll = New Collection 

    Dim arr As Variant 
    arr = Array(1, 2, 3) 

    'Add the array to the collection (makes a copy) 
    coll.Add arr 

    'Change the ooriginal array 
    arr(0) = 4 

    Debug.Print coll(1)(0), arr(0) 'Prints 1,4 

End Sub 

但它聽起來像你想引用工作。爲此,您的函數將需要返回一個對象/類實例,然後將其添加到集合中。

如果你的函數旨在返回Range,提交作業demo_1 = import_demo(1, nb_var)隱含調用Range.[_Default]屬性(相當於Range.Value)。爲了返回Range對象,您需要使用關鍵字SetSet demo_1 = import_demo(1, nb_var)

+0

謝謝。這很清楚。你能推薦一些關於你幫助我的那類信息的文章或文章嗎? – Arsen

+0

excel-vba https://stackoverflow.com/documentation/excel-vba/topics是一個很好的開始 – ThunderFrame

+0

的地方,如果你用正確的類型聲明變量而不是變體,那麼事情會變得更加混亂。 –