Copy classes between collections

  • Thread starter Thread starter Baz Star
  • Start date Start date
B

Baz Star

I must have missed something somewhere, but having
created a colection of class objects, each of which
contains a collection of other classn objects (nested 4
deep), I need to manipulate certain levels of the
hierarchy without affecting the original structure.
However creating a new collection and copying an object
across (using ByVal and declaring a new object) looks
like a copy has been made. However, manipulating this
object results in the original object also being changed.
Since referencing is by value, and a new collection
created, I would have thought the copied class would have
been unrelated to the original, but not so it seems.
Repeating the exercise using classes in VB6 gave the same
result. Short of creating new class objects and setting
the properties one by one (which proves tedious given the
sub collections), what is the best way to achieve an
object copy between collections in vba?
Regards.
 
Short of creating new class objects and setting
the properties one by one (which proves tedious given the
sub collections), what is the best way to achieve an
object copy between collections in vba?

There's no direct way to do this. A direct assignment using Byval gives
you a shallow reference (pointing to the same instance of the object) as
you found out. If you have nesting, then only the class knows about the
heirarchy and type and copying memory pointers won't give you a deep
copy. You'll pretty much limited to creating a new method 'Clone' and
managing all population yourself.

Public Function Clone as MyClass
Dim c as MyClass
Set c=new MyClass
set c.SomeCollection = new VBA.Collection
' add all items from internal collection
' to c.somecollection
' set properties
' etc...
set Clone = MyClass
End Function

-- Dev
 
Thanks Dev,

I guess I'll have to work along those lines. It'll add a
few more days to the work, but the speed gains of 50-100
times over using forms/queries makes it worth it. Couple
that with the additional control over data integrity.

Baz
 
the speed gains of 50-100
times over using forms/queries makes it worth it. Couple
that with the additional control over data integrity.

Be sure to consider code maintenance though.... Any changes in
classes/collections need to be updated in the Clone method.

-- Dev
 
Back
Top