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

1

The code below creates Labels dynamically based on a vector, it happens that I did not succeed in trying to delete (destroy) these objects.

I tested the 'Nothing' and other features indicated, but none worked, that is, the Labels remain on 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 the project (without changing or closing the form).

I submit the code below one of the attempts to destroy the Labels, but it did not work. One comment: I also tried to destroy the Labels created inside the creation routine (at the end of it) to test, but in this case it did not work either.

How do I do this?

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
    
asked by anonymous 17.03.2016 / 23:42

2 answers

2

To delete the label should be used in the same way as in the 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
    
18.03.2016 / 13:25
0

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

I made several attempts and came up with a solution that could 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
    
19.03.2016 / 18:06