How to create objects dynamically based on vector? (VBA / Excel)

1

I created two Labels dynamically based on a vector according to the code below, however, in the form only the last Label created (NewLabel1) remains, both the first (NewLabel0) and the Label that I used the base for the creation of the other two (Label1) do not remain.

I need to create several Labels according to the number of items I want to work on (one for each product of a certain line of cosmetics, for example), so the need to use a vector. How can I solve this?

Dim NewLabel(1) As Object

Set NewLabel(0) = Label1 'Label1 existe no formulário
Set NewLabel(1) = Label1

With NewLabel(0)
 .Caption = "NewLabel0"
 .Top = 0
 .Left = 0
End With

With NewLabel(1)
 .Caption = "NewLabel1"
 .Top = 20
 .Left = 20
End With

...
...
...

NewLabel(0).Delete
NewLabel(1).Delete
    
asked by anonymous 17.03.2016 / 02:57

2 answers

2

At some point I needed to use this code, check if you can adapt for yourself.

Private Sub UserForm_Initialize()
i = 1
maxBoxes = 3
    For idx = 1 To maxBoxes
            Set newBox = Me.Controls.Add("Forms.TextBox.1")
            With newBox
                .Tag = "new" & .Name
                    .Left = 55 * idx
                    .Top = 10
                    .Width = 50
                    .Text = "Exemplo" & i
            End With

            Set newBox1 = Me.Controls.Add("Forms.TextBox.1", "txt-" & i)
            With newBox1
                .Tag = "new" & .Name
                    .Left = 55 * idx
                    .Top = 25
                    .Width = 50
            End With
            i = i + 1
        Next
End Sub

    
17.03.2016 / 09:23
1

It worked very well! Below is the suggested adaptation for my case (using vector). Thanks!

Dim i As Integer
Dim NewLabel(3) As Object

For i = 0 To 3
 Set NewLabel(i) = Me.Controls.Add("Forms.Label.1")
 With NewLabel(i)
  .Tag = "NewLabel" & i 'Usar no lugar de "Name"
  .Caption = .Tag 'Name inicia do Label2 pois existe o Label1 no formulário
  .Top = 50 * i
  .Left = 50
End With

Next i
    
17.03.2016 / 12:33