vbacoreldraw

How to merge duplicate data in a single array/dictionary and return values?


I've written a VBA macro for CorelDraw that loops through selected objects and returns values as a string. I want it to be able to handle duplicate data better, for example if two objects have the same size, it should return

"2 of 10 x 10"

instead of

"1 of 10 x 10"
"1 of 10 x 10"

Coming from Ruby (specifically thinking of hashes), I'm thinking that the macro should loop through the selected range, add (object.sizeWidth, object.sizeHeight) data as strings to an array/dictionary where it should be checked for duplicates and count them. I don't know what's best or how to set/check their values.

Here is my code so far

Sub objectsToString()

Dim str As String
Dim v As Shape, vr As ShapeRange
Dim xSize#, ySize#
Dim dupCount As Integer

str = ""
Set vr = ActiveSelectionRange

    For Each v In vr
    dupCount = 'value assigned via iteration
    xSize = v.SizeWidth
    ySize = v.SizeHeight
    str = str & dupCount & " of " & xSize & " x " & ySize & vbNewLine

    Next v

 End Sub

Solution

  • Use scripting.dictionary using the shape name as key for example, and use it's .exists method then have the item as the count and have a separate dictionary with the same key name, and then have a class/type/array/collection/dictionary with the dimensions in.

    Something like this would be a good start.

    Sub x()
    
    Dim a() As Variant
    Dim d As Scripting.Dictionary
    Dim v As Variant
    
    a = Array("10 x 10", "20 x 20", "30 x 30", "10 x 10")
    
    Set d = New Scripting.Dictionary
    
    For Each v In a
    
        If Not d.Exists(v) Then
            d.Add v, 1
        Else
            d(v) = d(v) + 1
        End If
    
    Next v
    
    For Each v In d.Keys
    
        Debug.Print d(v) & " of " & v
    
    Next v
    
    End Sub
    

    Gives the result

    2 of 10 x 10

    1 of 20 x 20

    1 of 30 x 30