How to create dynamic variable names VBA

A dictionary would probably help in this case, it’s designed for scripting, and while it won’t let you create “dynamic” variables, the dictionary’s items are dynamic, and can serve similar purpose as “variables”.

Dim Teams as Object
Set Teams = CreateObject("Scripting.Dictionary")
For i = 1 To x
    Teams(i) = "some value"
Next

Later, to query the values, just call on the item like:

MsgBox Teams(i)

Dictionaries contain key/value pairs, and the keys must be unique. Assigning to an existing key will overwrite its value, e.g.:

Teams(3) = "Detroit"
Teams(3) = "Chicago"
Debug.Print Teams(3)  '## This will print "Chicago"

You can check for existence using the .Exist method if you need to worry about overwriting or not.

If Not Teams.Exist(3) Then
    Teams(3) = "blah"
Else:
    'Teams(3) already exists, so maybe we do something different here

End If

You can get the number of items in the dictionary with the .Count method.

MsgBox "There are " & Teams.Count & " Teams.", vbInfo

A dictionary’s keys must be integer or string, but the values can be any data type (including arrays, and even Object data types, like Collection, Worksheet, Application, nested Dictionaries, etc., using the Set keyword), so for instance you could dict the worksheets in a workbook:

Dim ws as Worksheet, dict as Object
Set dict = CreateObject("Scripting.Dictionary")
For each ws in ActiveWorkbook.Worksheets
    Set dict(ws.Name) = ws
Next

Leave a Comment