2008-10-20 196 views
7

是否有通用的方法克隆VBA中的對象?所以我可以將x複製到y而不是隻複製指針?在VBA中克隆對象?

Dim x As New Class1 
    Dim y As Class1 

    x.Color = 1 
    x.Height = 1 

    Set y = x 
    y.Color = 2 

    Debug.Print "x.Color=" & x.Color & ", x.Height=" & x.Height 

通過仿製我的意思是像Set y = CloneObject(x),而不是創建自己的方法爲類複製其屬性逐個。

回答

6

OK,這裏的東西,說明它開始:

創建一個類,調用它,哦,「Class1」:

Option Explicit 

Public prop1 As Long 
Private DontCloneThis As Variant 

Public Property Get PrivateThing() 
    PrivateThing = DontCloneThis 
End Property 

Public Property Let PrivateThing(value) 
    DontCloneThis = value 
End Property 

現在我們需要給它一個克隆函數。在另一個模塊,試試這個:

顯式的選項

Public Sub makeCloneable() 

Dim idx As Long 
Dim line As String 
Dim words As Variant 
Dim 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 With 

End Sub 

運行這一點,下面被添加到Class

Public Function Clone() As Class1 
Set Clone = New Class1 
Clone.prop1 = prop1 
Clone.PrivateThing = PrivateThing 
End Function 

...它看起來像一個開始。很多事情我會清理(可能會 - 這原來很有趣)。一個很好的正則表達式來尋找gettable/lettable/settable屬性,重構成幾個小函數,代碼去除舊的「Clone」函數(並且把新的函數放在最後),一些更多的Stringbuilder-ish去幹(Don' t重複你自己)連接,這樣的東西。

+0

好主意邁克,雖然我懷疑手動維護克隆方法可能會更容易在我的情況。非常好的主意,但。 – 2008-10-20 22:40:13

1

我不認爲有什麼內置的,但它會很好。

我認爲至少應該有一種方法來使用VBA編輯器自動創建一個Clone方法。我去看看我能看看這一次我已經得到了孩子們上牀睡覺......

1
Private pOldinfo As YourClass 

Public Property Set clone(ByVal Value As YourClass) 
    Set pOldinfo = Value 
End Property 

ByVal關鍵字應該可以解決您的問題。