Dynamically Create Dynamic Arrays in VBA

前端 未结 3 1337
离开以前
离开以前 2021-01-13 15:33

My objective is to use an array of names to create dynamic variables in VBA, heres the code:

Sub mymacro()
Dim names()
names = Array(\"cat_code()\", \"dog_co         


        
3条回答
  •  长情又很酷
    2021-01-13 16:03

    VBA can't really do what you're trying to do without getting into a horrible world of complications.

    How about using a VBA Collection object instead? You'll need to create a simple class to hold the number, because VBA collections work with references, not values.

    So I created a Class and set its name to "AnimalCounter", with this content:

    Public Counter As Integer
    

    Then your macro becomes something like this:

    Sub mymacro()
    
    Dim coll As New Collection
    Dim c As Variant
    Dim ac As AnimalCounter
    
        For Each c In Array("cat", "dog", "eagle")
            Set ac = New AnimalCounter
            coll.Add ac, c
        Next
    
        Debug.Print coll("cat").Counter ' what's in "cat"?
        coll("dog").Counter = coll("dog").Counter + 1 ' update "dog" by one
        Debug.Print coll("dog").Counter ' "dog" should now be one more
    
    End Sub
    

    If you wanted arrays, put an array in to the class. Or another Collection, maybe?

提交回复
热议问题