Set b = a will not copy a to b. It only changes the reference.Code:Dim a As Object
Dim b As Object
Set b = a
How do I copy objects just like in C++?
Printable View
Set b = a will not copy a to b. It only changes the reference.Code:Dim a As Object
Dim b As Object
Set b = a
How do I copy objects just like in C++?
You have to copy it manually. Setting A=B, only makes A & B reference the same object. So, depending on what Object is, perform necessary action to reproduce it. For example, if it were a picture, use LoadPicture() to load the image into a different object. If it were a custom class you created, you should build a function that copies itself to a new passed object, initialized with the keyword New: Set [variable] = New [Object]
wow..Quote:
Originally Posted by LaVolpe
ok
my object here is collection (of a thousand elements).
so the only way is to use for each statement to copy the elements?
More or less. But why would you need to copy it? And based on that answer does the entire collection need to be copied? Maybe explaining the scenario might lead to alternate solutions.
Quote:
Originally Posted by LaVolpe
Code:Dim a As New Collection
Dim i As Integer
a.Add 4
a.Add 5
a.Add 6
i = my_function(a)
Private Function my_function(ByVal x As Collection) As Integer
'This function makes some undersired changes to the original collection and returns a value
'The original collection needs to be reserved
'Despite Byval statement, the object is passed by reference
Dim h As New Collection
Set h = x 'still fails
End Function
Is your collection only going to contain single numbers? If so, use an array instead of a collection and you can copy that easily enough.
Regarding your error: h.Add a.Item(x)
or use a For Each loop, but you'll still need h.Add
Nope,Quote:
Originally Posted by LaVolpe
the collection stores objects (defined by class module)
In that case, sounds like creating your "Clone" function withn the class may be the solution. Now is the entire collection modified? If not, don't clone the entire collection, only clone the ones that will be modified.
A rather simple clone function looks like this
Of course if the classes themselves store objects, then things get a bit more complicated.Code:Public Sub CloneMe(toObject As Class1) ' change class name
Set toObject=New Class1
' now populate all the properties
toObject.PropertyName = Me.PropertyName
' etc, etc
End Sub
Additionally, what gets changed that needs to be preserved, maybe just making a copy of those specific things will do the trick.