如何创建动态变量名称VBA

时间:2016-07-07 20:04:27

标签: excel vba excel-vba

我正在尝试根据单元格中的值在VBA中创建动态数量的变量。 基本上我最终想要的是Team1, Team2... to TeamX。 非常感谢任何帮助

Dim i, x As Integer
Set x = Range("J4").Value
Dim Team(1 To x) As String
Dim Manager(1 To x) As String
Range("A3").Select
For i = 1 To x
Dim Team(i) As Integer

2 个答案:

答案 0 :(得分:15)

在这种情况下,字典可能会有所帮助,它是专为编写脚本而设计的,虽然它不会让你创建"动态"变量,字典的项目是动态的,并且可以用作与变量"类似的目的。

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

稍后,要查询值,只需调用项目,如:

MsgBox Teams(i)

字典包含键/值对,键必须是唯一的。分配给现有的密钥将覆盖其值,例如:

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

如果您需要担心是否覆盖,可以使用.Exist方法检查是否存在。

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

End If

您可以使用.Count方法获取字典中的项目数。

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

字典的键必须是整数或字符串,但值可以是任何数据类型(包括数组,甚至是Object数据类型,例如CollectionWorksheetApplication,嵌套字典等,使用Set关键字),例如,您可以在工作簿中输入工作表:

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

答案 1 :(得分:1)

这将帮助您入门。但在开始之前,我建议您在Youtube上观看这些WiseOwlTutorials教程:

    Dim i, x As Integer
    x = Range("J4").Value
    Dim Team() As Integer
    Dim Manager() As String

    ReDim Team(1 To x) As Integer
    ReDim Manager(1 To x) As String

    Range("A3").Select


    For i = 1 To x

        Team(i) = i

    Next