Ali_R4v3n
Ali_R4v3n

Reputation: 377

vba passing an array to a Dictionary.keys

i have an array of strings MyStrArray and i have a dictionary object MyDict

How do I pass MyStrArray to MyDict.keys Without looping? is it possible?

if i try MyDict.keys = MyStrArray I get an error "object Doesn't support this method" and the keys bounds are MyDict.Keys(0 to -1)i know what that means and i know i can loop through the array to fill the dict. as such (simple example)

on error resume next 
    for i= Lbound(MyStrArray) To Ubound(MyStrArray)
    MyDict.add key:=MyStrArray(i), item:=whatever
    next i

so, is there a way around that??

Upvotes: 4

Views: 7621

Answers (1)

user3598756
user3598756

Reputation: 29421

the straight answer is "NO".

The following just in case you would consider a helper to just avoid looping in the main code

Option Explicit

Sub main()

Dim myDict As Dictionary

Dim myArr As Variant
myArr = Array("a", "b", "b")

Set myDict = GetDict(myArr)

End Sub


Function GetDict(keysArray As Variant) As Scripting.Dictionary
Dim dict As New Scripting.Dictionary
Dim i As Long
For i = LBound(keysArray) To UBound(keysArray)
    dict.Add Key:=keysArray(i), Item:=i
Next i
Set GetDict = dict
End Function

Upvotes: 1

Related Questions