Home » excel » excel – Can we assign the dictionary keys to a column with a single statement?

excel – Can we assign the dictionary keys to a column with a single statement?

Posted by: admin April 23, 2020 Leave a comment

Questions:

I have large dictionary keys,Which I want to insert to a column of an excel sheet.Which I have done by the below :

Dim a, d, i 'Create some variables
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Athens" 'Add some keys and items.
d.Add "b", "Belgrade"
d.Add "c", "Cairo"

a = d.keys 'Get the keys

For i = 0 To d.Count - 1 'Iterate the array
    ob.Cells(i + 1, 1).Value = a(i)
Next

But can it be done in one statement? say obj2.Cells(1,1).Resize(dicP.Count,1)=a I tried this one also but it is putting only the first key in the range I defined by Resize.

How to&Answers:

Like this?

Sub a()
    Dim d '<~~ Create some variable
    Dim sKeys()

    Set d = CreateObject("Scripting.Dictionary")
    d.Add "a", "Athens" 'Add some keys and items.
    d.Add "b", "Belgrade"
    d.Add "c", "Cairo"

    '~~> Get dictionary Keys
    sKeys = d.keys

    Range("A1").Resize(d.Count) = Application.Transpose(sKeys)
End Sub