Edward de Goeij
Edward de Goeij

Reputation: 87

Filling up an array with a user input key

I need to write an array that can store an input value from a use a key and another variable as a value

So a real simple example of what I want to achieve is:

Sub addValuesToArray()

 Dim aRandomVar as String
 aRandomVar = "test"

 Dim myArray() as String

 userInput = inputBox("How do you want to call this variable")
 myArray(userInput) = aRandomVariable

End sub

However, running this gives me a type 9 error. Any thoughts on what I should improve?

Upvotes: 0

Views: 41

Answers (1)

Alex P
Alex P

Reputation: 12487

I'd use a dictionary like this:

Sub addValuesToArray()
    Dim aRandomVar As String, dic As Object

    Set dic = CreateObject("Scripting.Dictionary")
    aRandomVar = "test"

    userinput = InputBox("How do you want to call this variable")

    dic.Add userinput, aRandomVar

    For Each Key In dic.Keys
        Debug.Print "Key: " & Key & " Value: " & dic(Key)
    Next
End Sub

Upvotes: 1

Related Questions