1

For example, I have some data in an excel sheet 'MySheet' as follows:

sepal petal
5 11
4 12
3 13

I need to convert these data into a dictionary follows after calling a VBA function named dict= ex_dict () where I can access to each key like :

dict=ex_dict(A1:B4)
dict= {"sepal": [5,4,3], "petal": [11,12,13]}

Or

dict ('sepal')= [5,4,3]

Initially, I thought I have found a solution. But later I have found that given solutions are output as string but not as Dictionary object

0

3 Answers 3

2

Columns to String

Function ex_dict(ByVal rg As Range) As String
    
    Dim rCount As Long: rCount = rg.Rows.Count
    If rCount < 2 Then Exit Function
    
    ex_dict = "{"
    
    Dim crg As Range
    Dim r As Long
    
    For Each crg In rg.Columns
        ex_dict = ex_dict & """" & crg.Cells(1).Value & """: ["
        For r = 2 To rCount
            ex_dict = ex_dict & crg.Cells(r).Value & ","
        Next r
        ex_dict = Left(ex_dict, Len(ex_dict) - 1) & "], "
    Next crg
    
    ex_dict = Left(ex_dict, Len(ex_dict) - 2) & "}"

End Function
Sign up to request clarification or add additional context in comments.

1 Comment

Hi, Thanks for your code. The output is a string but not a dictionary. I need as a dictionary so that I can access them later with the keys to each item
1

Please, use the next function:

Function ex_dictX(rng As Range) As String
   Dim dict As Object, i As Long, j As Long, arr, strIt As String
   
   Set dict = CreateObject("Scripting.Dictionary")
   
   arr = rng.Value2: strIt = "["
   For i = 1 To UBound(arr, 2)
       For j = 2 To UBound(arr)
            strIt = strIt & arr(j, i) & ","
       Next j
        dict.Add Chr(34) & arr(1, i) & Chr(34) & ": ", left(strIt, Len(strIt) - 1) & "]"
        strIt = "["
   Next i
   'build the string to be returned (as pseudo dictionary):
   For i = 0 To dict.count - 1
        strIt = strIt & dict.Keys()(i) & dict.items()(i) & ", "
   Next
 
   ex_dictX = "{" & left(strIt, Len(strIt) - 2) & "}"
End Function

It can be tested with a simple Sub:

Sub tesTex_dict()
    Debug.Print ex_dict(Range("A1:B4"))
End Sub

or call it as UDF (User Defined Function) from a cell as:

 =ex_dict(A1:B4)

Edited:

Please, test the next version which returns a Scripting.Dictionary:

Function ex_dictD(rng As Range) As Object
   Dim dict As Object, i As Long, j As Long, arr, strIt As String
   
   Set dict = CreateObject("Scripting.Dictionary")
   
   arr = rng.Value2: strIt = "["
   For i = 1 To UBound(arr, 2)
       For j = 2 To UBound(arr)
            strIt = strIt & arr(j, i) & ","
       Next j
        dict.Add Chr(34) & arr(1, i) & Chr(34), left(strIt, Len(strIt) - 1) & "]"
        strIt = "["
   Next i
 
   Set ex_dictD = dict
End Function

It can be tested in a Sub like the following one:

Sub testEx_dict()
    Dim dict As Object, i As Long
    Set dict = ex_dictD(Range("A1:C4"))
    
    For i = 0 To dict.count - 1
        Debug.Print dict.Keys()(i) & " = " & dict.items()(i)
    Next
End Sub

8 Comments

Thanks for your code. It works for 2 columns but if I select more than 2 columns like (A1:D4) then it still prints 2 columns. I am totally new in VBA and I can not edit your sample code. But I have found a solution in the next comment from @VBasic2008
@Md Asraful Kabir But asked for a function able to extract that string you name it as 'dictionary' from that specific range. It is not complicate to adapt the function in a way to return that string pattern for any columns and rows (which you should state in your question...). Even if you received an answer, I will adapt the function to do that. Also, using a Scripting.Dictionary, which I also thought it is a requirement...
@Md Asraful Kabir Adapted...
Hi, Thanks for updated code. The output is a string. like "{"sepal": [5,4,3], "petal": [11,12,13]}" .But I want final output as type dict
@Md Asraful Kabirv What do you mean by "as type dict"? Don't you want it as a string in a cell, as requested in your question? Anyhow, all the necessary data is inside of the dict dictionary. The above code only transform its data in the way you required... Do you understand the code we are talking about?
|
1

Using the Dictionary Object.

Sub Example()
    'Create a Dictionary object
    Dim sepal As Object
    Set sepal = CreateObject("Scripting.Dictionary")
    
    'Loop through the table
    Dim Cell As Range
    For Each Cell In Range("A2:A5")
        'Add unique entries to the dictionary
        If Not sepal.exists(Cell.Value) Then
            'Add cell value as the Key & the adjacent value as the Item.
            sepal.Add Cell.Value, Cell.Offset(, 1).Value
        End If
    Next
    
    Debug.Print sepal(4) 'returns 12
    Debug.Print sepal(3) 'returns 13
End Sub

After building the dictionary, sepal.Keys returns the array [5,4,3] and sepal.Items returns the array [11,12,13].

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.