0

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?

1
  • First of all aRandomVariable is never declared! Secondly, you can't use an array for key/value pairs. Check outcollection... Commented Jun 16, 2017 at 7:03

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the quick reply!

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.