How to remove a Label that was created dynamically in VBA?

Asked

Viewed 256 times

2

The code below, sent by Luiz Vieira, creates Labels dynamically and a click treatment function for each Label.

I would like to know how to use the Click event to remove the dynamically created Labels.

Creating the Labels:

Dim Labels() As New LabelHandler

Private Sub CriaLabels(ByVal QuantidadeDeLabels As Integer)

    Dim i As Integer
    Dim Label As Control

    ReDim Labels(0 To QuantidadeDeLabels - 1)

    For i = 0 To QuantidadeDeLabels - 1

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

        With Label
          .Caption = "NewLabel" & i
          .Top = 50 * i
          .Left = 50
        End With

        Set Labels(i).Ctrl = Label

    Next i

End Sub

Click treatment function in the class module:

Public WithEvents Ctrl As MSForms.Label

Private Sub Ctrl_Click()

    MsgBox "Você clicou no label de nome " & Ctrl.Name

End Sub

1 answer

0


Edelson, use the instruction below:

Me.Controls.Remove Labels(0).Name

Change the index to delete the desired label, in this case the index is zero.

I usually delete from the last index until the first, to avoid problems.

  • Thanks Leo! I adapted the code to my project and it worked perfectly. I’ll post below in case anyone needs it:

  • Option Explicit Public Withevents Ctrl As Msforms.Label Private Sub Ctrl_click() 'Deleta Labels created dynamically Dim i As Integer If Ctrl.Name = "Newlabel3" Then For i = 0 To 3 Ctrl.Name = "Newlabel" & i Form1.Controls.Remove Ctrl.Name Next i End If End Sub

  • You’re welcome, good job!

Browser other questions tagged

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