向userform添加多个动态控件,并为其分配不同的事件处理程序

时间:2016-03-04 06:36:23

标签: vba excel-vba excel

我正在尝试添加多个旋转按钮,每个按钮都链接到分配了一些值的不同单元格集。我已经尝试添加控件并使用类模块向它们添加事件处理程序过程,但无济于事。任何帮助将不胜感激。

Dim spinArray() As New Class1
Private Sub UserForm_Initialize()
Dim i As Long
Dim quantspin As MSForms.SpinButton


subassy_break.Height = pnum1 * 70
subassy_break.Width = 500
With Label_Var    
    .Top = 15
    .Left = subassy_break.Width - (Label_Var.Width + 15)
    .Caption = msg
    .AutoSize = True
    .Font.Bold = True
End With

With UserForm
 For i = 1 To pnum1
    Set quantspin = Me.Controls.Add("Forms.spinbutton.1", "Quantity_Count_"  & i)
     With quantspin
       .Min = 0
       .SmallChange = 1
       .Max = 1
       .Left = 200
       .Top = subassy_break.height- pnum1*20
     End With
Next i
End With
End Sub

我添加的新类模块也是

Public WithEvents spinevents As MSForms.SpinButton

Private Sub spinevents_change()
    For i = 1 To pnum1
        Cells(userow + i, usecol).Value = spinevents.Value
    Next i
End Sub

1 个答案:

答案 0 :(得分:0)

这应该可以帮助你解决这个问题:

clsSpin

Public WithEvents spinevents As MSForms.SpinButton
Public TargetCell As Range  '<<the cell to operate on

Private Sub spinevents_change()
    TargetCell.Value = spinevents.Value
End Sub

UserForm(简化显示相关部分)

Dim spinners As Collection '<<< holds your clsSpin objects

Private Sub UserForm_Initialize()
    Dim i As Long, s As clsSpin, quantspin

    Set spinners = New Collection


    For i = 1 To 5
        Set quantspin = Me.Controls.Add("Forms.spinbutton.1", "Quantity_Count_" & i)
        With quantspin
            .Min = 0
            .SmallChange = 1
            .Max = 100
            .Left = 20 * i
            .Top = 50
        End With

        'create a new instance of the class, set some properties
        '  and add it to the collection
        Set s = New clsSpin
        Set s.spinevents = quantspin
        Set s.TargetCell = ThisWorkbook.Sheets(1).Cells(i, 1)
        spinners.Add s

    Next i

End Sub