Excel VBA Assignment by value or by reference?

只愿长相守 提交于 2021-02-10 13:29:14

问题


I have two objects of the same class which have a property that's an array of doubles (Double()), and I would like to do the following:

Obj1.arr_property = Obj2.arr_property

Is the above going to assign by value or by reference? If by reference, how to make it by value instead?


回答1:


Everything that you assign with Set only copies the reference to the new variable, not the data. You do not use Set, so all values of the array are copied, not just the reference to the array.

You actually cannot use Set in this case, even if you'd want to. Set is only allowed for objects. Arrays are no objects, so they can only be assigned the way you did.

Things are a bit different if you do not use the assignment operator =, but pass a value to a function. But that is another question.




回答2:


This will copy the values, not the reference, into Obj1.arr_property.

One important thing to keep in mind is that the destination array must be dynamic/re-sizable. This means it needs to be declared in this form,Dim arr_property() As Double, rather than something like Dim arr_property(10) As Double. Otherwise you will get a Can't assign to array error.



来源:https://stackoverflow.com/questions/36945129/excel-vba-assignment-by-value-or-by-reference

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!