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

Asked

Viewed 763 times

1

The code below creates Labels dynamically based on an array, occurs that I did not succeed in trying to eliminate (destroy) these objects.

I tested 'Nothing' and other features indicated, but none worked, IE, Labels remain in the form. As in the application each project that is selected will have a different number of Labels to be created, I need to destroy them when changing project (without changing or closing the form).

I present the code below one of the attempts to destroy the Labels, but it did not work. One remark: I also tried to destroy the Labels created within the creation routine itself (at the end of it) to perform tests, but also in this case did not work.

How should I do it?

Private Sub CriaLabels(ByVal QuantidadeDeLabels As Integer)

Dim i As Integer

Dim NewLabel(QuantidadeDeLabels-1) As Object

For i = 0 To QuantidadeDeLabels-1

 Set NewLabel(i) = Me.Controls.Add("Forms.Label.1")

 With NewLabel(i)
  .Tag = "NewLabel" & (i-1) '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

End Sub



Private Sub DestroiLabels(ByVal QuantidadeDeLabels As Integer)

Dim i As Integer

For i = 0 To QuantidadeDeLabels-1

 NewLabel(i).Delete 'NÂO FUNCIONOU ASSIM!!!

Next i

End Sub

2 answers

2


To exclude the label should be used in the same way as in construction:

Private Sub deleteLabel_Click()

Dim MyLabel(0) As Object

Set MyLabel(0) = Me.Controls.Add("Forms.Label.1")

    With MyLabel(0)
        .Name = "Label99" 'Nome de seu Label
    End With

    Me.Controls.Remove MyLabel(0).Name

End Sub
  • It worked! Thank you!

0

Evert, the solution presented only works within the same routine, when I created a separate routine to delete these objects, it didn’t work.

I made several attempts and came up with a solution that can be improved, for example, in case of having different type objects created in the same form (like Labels and Textbox) without being in ascending order:

Private Sub DestroiLabels(ByVal QuantidadeDeLabels As Integer)

Dim i As Integer

For i = Me.Controls.Count - 1 To Me.Controls.Count - QuantidadeDeLabels Step -1

  Me.Controls.Remove (Me.Controls(i).Name)

Next i

End Sub

Browser other questions tagged

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