How to add objects into and array

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Rodney Roe
    New Member
    • Oct 2010
    • 61

    How to add objects into and array

    I'm using VBA in excell 2007. I have a userform with 42 butons with their names ranging from dy1 to dy42. Is there a way to put these objects into an array without listing each one? In other words I would like to use the for...next loop to add them incrementally if possible. This way I can call which ever button I need when I need it. Previously I was incrementing a string and then calling the button with a select case function, and i've just discoverd how versatile arrays are but I'm still trying to learn them.

    If you could help,
    Thnx
  • Guido Geurs
    Recognized Expert Contributor
    • Oct 2009
    • 767

    #2
    Is it possible to attach Your XLS in Bytes?
    So I can better understand what You exactly want and we will work on the same data!

    Comment

    • Rodney Roe
      New Member
      • Oct 2010
      • 61

      #3
      Here is a small example:

      Code:
      'declaration
      Dim button(1 To 6) As Object
      
      'code
      Private Sub UserForm_Initialize()
      Dim d As Integer
      
      Set button(1) = CommandButton1
      Set button(2) = CommandButton2
      Set button(3) = CommandButton3
      Set button(4) = CommandButton4
      Set button(5) = CommandButton5
      Set button(6) = CommandButton6
      
      For d = 1 To 6
      button(d).BackColor = &H8011EE
      Next
      End Sub
      ,but what i'd really like is something like this;

      Code:
      'declaration
      Dim button(1 To 6) As Object
      
      'code
      Private Sub UserForm_Initialize()
      Dim d As Integer
      
      For i = 1 To 6
          Set button(i) = CommandButton(i)
      Next
      
      For d = 1 To 6
      button(d).BackColor = &H8011EE
      Next
      End Sub
      I'm not sure how or if it's possible since and object isn't a string and that's the hurdle i'm trying to jump.

      Comment

      • Guido Geurs
        Recognized Expert Contributor
        • Oct 2009
        • 767

        #4
        I hope this will help:
        Code:
        'declaration
        Dim button(1 To 6) As Object
          
        'code
        Private Sub UserForm_Initialize()
        Dim d As Integer
           For d = 1 To 6
              Set button(d) = Controls("commandbutton" & d)
              button(d).BackColor = &H8011EE
           Next
        End Sub

        Comment

        • Rodney Roe
          New Member
          • Oct 2010
          • 61

          #5
          You are soooo awsome!! :-) Worked perfectly, Thanks.

          Comment

          Working...