Create a Series of dynamically created button by clicking each of them in Excel VBA

后端 未结 2 1188
北荒
北荒 2021-01-16 11:50

Please don\'t consider this question as a repeated question! This question is clearly different from earlier similar-looking queries.

2条回答
  •  一个人的身影
    2021-01-16 12:23

    Can you try this. A bit rushed, so wouldn't be surprised if something goes wrong, but will come back tomorrow if so.

    Behind the form

    Private col As Collection
    
    Private Sub UserForm_AddControl(ByVal Control As MSForms.Control)
    
    Dim cl As Class2
    Dim ctl As MSForms.CommandButton
    
    Set col = New Collection
    
    For Each ctl In Me.Controls
        Set cl = New Class2
        Set cl.btEvents = ctl
        col.Add cl
    Next ctl
    
    End Sub
    
    Private Sub UserForm_Initialize()
    
    Dim btEx As MSForms.CommandButton
    Set btEx = UserForm1.Controls.Add("Forms.CommandButton.1")
    
    With btEx
        .Top = 12
        .Left = 12
        .Width = 72
        .Height = 36
        .Caption = "Click Me"
    End With
    
    End Sub
    

    Class module The only change here is to add some spacing so the buttons don't appear on top of each other.

    Public WithEvents btEvents As MSForms.CommandButton
    
    Private Sub btEvents_click()
    
    Dim btEx As MSForms.CommandButton
    Set btEx = UserForm1.Controls.Add("Forms.CommandButton.1")
    
    With btEx
        .Top = 30 * UserForm1.Controls.Count
        .Left = 30
        .Width = 72
        .Height = 36
        .Caption = "Click Me"
    End With
    
    End Sub
    

提交回复
热议问题