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

Asked

Viewed 1,416 times

1

I created two Labels dynamically based on a vector according to the code below, however, in the form only remains the last Label created (Newlabel1), both the first (Newlabel0) and the Label I used as the basis for creating 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 cosmetics line, for example), so the need to use a vector. How can I fix 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

2 answers

2


At a time I needed I used this code, see if you can adapt for you.

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

inserir a descrição da imagem aqui

1

It worked great! Below the suggested adaptation for my case (using vector). Grateful!

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.