VBA Deep Clone Dictionary

The solution for “VBA Deep Clone Dictionary” can be found here. The following code will assist you in solving the problem.

‘ Compare mode for cloning dictionary object
‘ See CloneDictionary function
Public Enum eCompareMethod2
ecmBinaryCompare = 0
ecmTextCompare = 1
ecmDatabaseCompare = 2
‘ Added this to use original compare method
ecmSourceMethod = 3
End Enum

‘ Procedure : CloneDictionary
‘ Author : Adam Waller
‘ Date : 3/30/2021
‘ Purpose : Recursive function to deep-clone a dictionary object, including nested
‘ : dictionaries.
‘ : NOTE: All other object types are cloned as a reference to the same object
‘ : referenced by the original dictionary, not a new object.

Public Function CloneDictionary(dSource As Dictionary, _
Optional Compare As eCompareMethod2 = ecmSourceMethod) As Dictionary

Dim dNew As Dictionary
Dim dChild As Dictionary
Dim varKey As Variant

‘ No object returned if source is nothing
If dSource Is Nothing Then Exit Function

‘ Create new dictionary object and set compare mode
Set dNew = New Dictionary
If Compare = ecmSourceMethod Then
‘ Use the same compare mode as the original dictionary.
dNew.CompareMode = dSource.CompareMode
dNew.CompareMode = Compare
End If

‘ Loop through keys
For Each varKey In dSource.Keys
If TypeOf varKey Is Dictionary Then
‘ Call this function recursively to add nested dictionary
Set dChild = varKey
dNew.Add varKey, CloneDictionary(dChild, Compare)
‘ Add key to dictionary
dNew.Add varKey, dSource(varKey)
End If
Next varKey

‘ Return new dictionary
Set CloneDictionary = dNew

End Function

Thank you for using DeclareCode; We hope you were able to resolve the issue.

More questions on [categories-list]

Similar Posts