在VBA中,我很难将事件分配给动态创建的标签。我想将tbEvents_Click分配给每个标签。
我上的是Class1
Option Explicit
Public WithEvents tbEvents As MSForms.Label
Private Sub tbEvents_Click()
MsgBox "You clicked label"
End Sub
和形式frMain
Dim HH As Long, VV As Long
Public tbPin As MSForms.Label
Dim Question As New Class1
Dim objMyEventClass As New Class1
Option Explicit
Private Sub UserForm_Initialize()
HH = shQuestions.Range("C1").CurrentRegion.Columns.Count
VV = shQuestions.Range("A3").CurrentRegion.Rows.Count
End Sub
Private Sub addQuestions()
Dim i As Long, j As Long
Dim mmm As String
For i = 1 To VV + 1
For j = 1 To HH + 1
Set tbPin = frMain.Controls.Add("Forms.Label.1", "label" & i & j, True)
With tbPin
If i = 1 Then
.Caption = "Question" & i & j
.Height = 80
.Top = 230
.BackColor = RGB(100, 116, 168)
Else
.Caption = "labelPoints" & i & j
.Height = 460 / VV
.Top = 310 + (i - 2) * (460 / VV)
.BackColor = RGB(0, 116, 168)
End If
If j = 1 Then
.Caption = "Points" & i & j
.Width = 325
.Left = 50
.BackColor = RGB(100, 116, 168)
Else
.Width = 750 / HH
.Left = 375 + (j - 2) * (750 / HH)
Set objMyEventClass.tbEvents = tbPin
End If
End With
Next j
Next i
End Sub
我希望
Set objMyEventClass.tbEvents = tbPin
将事件分配给所有标签。但它只将事件添加到最后创建的标签。我做错了什么?谢谢。
1条答案
按热度按时间wljmcqd81#
您正在创建
Class1
的多个示例(每个标签一个),因此您需要将它们存储在类似于Collection的地方,以便在addQuestions
sub完成后,它们都可以留在作用域中。下面是一个简化的示例
1类:
用户表单: