Cloning Objects in VBA? Cloning Objects in VBA? vba vba

Cloning Objects in VBA?


OK, here's the beginning of something that illustrates it:

Create a class, call it, oh, "Class1":

Option ExplicitPublic prop1 As LongPrivate DontCloneThis As VariantPublic Property Get PrivateThing()    PrivateThing = DontCloneThisEnd PropertyPublic Property Let PrivateThing(value)    DontCloneThis = valueEnd Property

Now we need to give it a Clone function. In another module, try this:

Option Explicit

Public Sub makeCloneable()Dim idx As LongDim line As StringDim words As VariantDim cloneproc As String' start building the text of our new function    cloneproc = "Public Function Clone() As Class1" & vbCrLf    cloneproc = cloneproc & "Set Clone = New Class1" & vbCrLf    ' get the code for the class and start examining it        With ThisWorkbook.VBProject.VBComponents("Class1").CodeModule        For idx = 1 To .CountOfLines            line = Trim(.lines(idx, 1)) ' get the next line            If Len(line) > 0 Then                line = Replace(line, "(", " ") ' to make words clearly delimited by spaces                words = Split(line, " ") ' so we get split on a space                If words(0) = "Public" Then ' can't set things declared Private                    ' several combinations of words possible                    If words(1) = "Property" And words(2) = "Get" Then                        cloneproc = cloneproc & "Clone." & words(3) & "=" & words(3) & vbCrLf                    ElseIf words(1) = "Property" And words(2) = "Set" Then                        cloneproc = cloneproc & "Set Clone." & words(3) & "=" & words(3) & vbCrLf                    ElseIf words(1) <> "Sub" And words(1) <> "Function" And words(1) <> "Property" Then                        cloneproc = cloneproc & "Clone." & words(1) & "=" & words(1) & vbCrLf                    End If                End If            End If        Next        cloneproc = cloneproc & "End Function"        ' put the code into the class        .AddFromString cloneproc    End WithEnd Sub

Run that, and the following gets added into Class1

Public Function Clone() As Class1Set Clone = New Class1Clone.prop1 = prop1Clone.PrivateThing = PrivateThingEnd Function

...which looks like a start. Lots of things I'd clean up (and probably will - this turned out to be fun). A nice Regular Expression to find gettable/lettable/settable attributes, refactoring into several small functions, code to remove old "Clone" functions (and put the new one at the end), something a bit more Stringbuilder-ish to DRY (Don't Repeat Yourself) up the concatenations, stuff like that.


Scott Whitlock has posted a fantastic answer to this problem on another question.


I don't think there's anything built in, although it would be nice.

I think there should at least be a way to create a Clone method automatically using the VBA Editor. I'll see if I can take a look at it once I've got the kids to bed...