【问题标题】:EXCEL VBA: dblClick, Repetitive Code ImprovementEXCEL VBA:dblClick,重复代码改进
【发布时间】:2013-07-19 22:03:55
【问题描述】:

我有一堆类似构造的用户窗体,上面有许多相同的对象。对于我的标签(超过 50 个),我创建了一个 dblClick 事件以允许用户更改标题。这一切都很好,但我想知道是否有办法改进我的代码。

有没有办法避免为了处理不同对象上的相同事件而制作数十份相同代码的副本?

这是我的代码:

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

我的用户表单中有超过 50 行这样的克隆代码。我认为有更好的方法可以做到这一点,但是当我 looked 使用 Class EventHandler 时,我看不到如何将其应用于我的目的。

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

谢谢,

埃利亚斯

【问题讨论】:

  • 您发布的链接应该适用于标签...

标签: excel vba events userform repeat


【解决方案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

【讨论】:

  • 谢谢。好吧,到目前为止,我的开端不错(我不得不研究“Collection”和“clsLabel”)。但是,问题在于双击操作不起作用。你能告诉我我做错了什么吗?
  • 嗯,它对我有用……很难说你的代码版本有什么问题。您是否尝试过调试以确保正在填充集合?
  • 我在“立即”窗口中输入了“print colLabels(1)”,但这不起作用。我对课程模块非常熟悉;在过去的 30 分钟里,我学到的东西比我知道的还要多。不过,我仍然无法让它发挥作用。 (Excel 2013)
  • 如果您在Set l.oLabel = o 上添加断点,它会在您的表单加载时进入断点吗?或者在该行之后添加Debug.print o.Name,然后查看立即窗口中的内容。
  • 是的,“Debug.print o.Name”正在工作。它只打印出我的表单中每个标签的名称。此外,断点在“Set l.oLabel = o”行处停止。是我的 clsLabel 有问题吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多