EXCEL VBA:dblClick,重复代码改进

时间:2013-07-19 22:03:56

标签: excel vba events userform repeat

我有一堆类似构造的用户表单,上面有许多相同的对象。对于我的标签(数量超过50),我创建了一个dblClick事件,允许用户更改标题。这样做很好 - & -all,但我想知道是否有办法改进我的代码。

有没有办法可以避免制作相同代码的几十个副本只是为了处理不同对象上的同一事件?

这是我的代码:

Private Sub Item1_Label_dblClick(ByVal Cancel as MSForms.ReturnBoolean)
    Item1_Label.Caption = InputBox("blah?", "blah", Item1_Label.Caption)
        if Item1_Label.Caption = "" Then Item1_Label.Caption = "Item 1"
End Sub

Private Sub Item2_Label_dblClick(ByVal Cancel as MSForms.ReturnBoolean)
    Item2_Label.Caption = InputBox("blah?", "blah", Item2_Label.Caption)
        if Item2_Label.Caption = "" Then Item2_Label.Caption = "Item 2"
End Sub

Private Sub Item3_Label_dblClick(ByVal Cancel as MSForms.ReturnBoolean)
    Item3_Label.Caption = InputBox("blah?", "blah", Item3_Label.Caption)
        if Item3_Label.Caption = "" Then Item3_Label.Caption = "Item 3"
End Sub

'etcetera etcetera

我的userform中有超过50个克隆代码行。我认为有更好的方法,但是当我looked使用Class EventHandler时,我无法看到如何将它应用于我的目的。

有没有办法防止这种重复的代码?

谢谢,

利亚

1 个答案:

答案 0 :(得分:2)

'clsLabel
Public WithEvents oLabel As MSForms.Label

Public Sub oLabel_dblClick(ByVal Cancel As MSForms.ReturnBoolean)
    MsgBox oLabel.Caption
End Sub



'form code
Private colLabels As Collection

Private Sub UserForm_Initialize()
Dim o As Control, l As clsLabel
Set colLabels = New Collection
For Each o In Me.Controls
    If TypeName(o) = "Label" Then
        Set l = New clsLabel
        Set l.oLabel = o
        colLabels.Add l
    End If
Next o
End Sub