EXCEL VBA: dblClick, Repetitive Code Improvement

拜拜、爱过 提交于 2019-12-13 04:37:01

问题


I have a bunch of similarly constructed userforms with many identical objects on them. For my labels (which number over 50), I have created a dblClick event to allow the users to change the caption. This is working fine-&-all, but I'm wondering if there's a way for me to improve my code.

Is there a way to be able to avoid making dozens of copies of the same code just to handle the same event on different objects?

Here is my code:

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

I have over 50 of these clone lines of code in my userform. I think there is a better way to do it, but when I looked up using a Class EventHandler, I couldn't see how to apply it for my purposes.

Is there a way to prevent this repetitive code?

Thanks,

Elias


回答1:


'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


来源:https://stackoverflow.com/questions/17756216/excel-vba-dblclick-repetitive-code-improvement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!