【问题标题】:Recreating an ActiveX control with VBA events, using VBA使用 VBA 重新创建带有 VBA 事件的 ActiveX 控件
【发布时间】:2017-03-08 01:34:33
【问题描述】:

我有一个组合框,该组合框绑定了多个事件(例如,ComboBox1_Change、Click、GotFocus、LostFocus)。出于我的目的,我需要使用 ActiveX 控件。

对于一些背景:

当机器连接到投影仪时,我遇到了 ActiveX 控件出现故障的问题。其他人也有同样的问题,但没有解决方案。我发现解决此问题的最佳方法是创建一个用户可以单击的附加按钮,该按钮会删除 ActiveX 控件并重新创建它。

问题是(和我的问题)...当我这样做时,VBA 事件不再执行。该控件的名称完全相同。是否有一个简单的修复(例如我可以设置的 ActiveX 控件中的属性),这样我就不需要编写 VBA 代码来删除和重写现有的 VBA 代码(我什至不能 100% 肯定会解决这个问题) ?

【问题讨论】:

  • 为了更好的帮助,您能否发布您正在修改的现有代码?
  • 控件是工作表还是用户窗体?

标签: vba excel activex


【解决方案1】:

这似乎对我有用,在工作表中:

从工作表上的 2 个命令按钮开始:CommandButton1CommandButton2

您无法单步执行代码,但它会运行。

Option Explicit

Private Sub CommandButton1_Click()
  Dim oldObj As OLEObject
  Dim left As Double, top As Double, width As Double, height As Double
  Set oldObj = Me.OLEObjects("CommandButton2")

  With oldObj
    'Rename the control to detach events
    .Name = "CommandTEMP"
    left = .left
    top = .top
    width = .width
    height = .height
    .Delete
  End With

  Dim newObj As Object

  Set newObj = Me.OLEObjects.Add(ClassType:="Forms.CommandButton.1", Link:=False _
        , DisplayAsIcon:=False, left:=left, top:=top, width:=width, height:=height)

  newObj.Name = "CommandButton2"

End Sub

Private Sub CommandButton2_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
  Me.CommandButton2.Object.Caption = Timer
End Sub

【讨论】:

  • 这似乎可以正常工作,但增加了一个问题……现在每当我点击组合框时,屏幕“抽搐”,光标在其他地方工作。没有触发任何 VBA 事件,因为我在每个模块上都设置了断点。发生这种情况后,我无法单击屏幕上的任何位置。我必须 alt-tab 到另一个窗口,然后 alt-tab 回到 Excel。
  • @ConfusedNoob 不要相信断点没有被命中。请注意,我说过您不能在某个点之后单步执行代码,并且从该点开始会忽略某些断点。使用debug.print 语句来确认代码被命中。
  • @ConfusedNoob 控件是工作表还是表单?
  • 控件在工作表上。关于 debug.print 的好建议,没想到...我在 debug.print 中添加了我的 VBA 代码中的每个事件。什么都没有触发...
  • 你可能处于设计模式吗?
猜你喜欢
  • 2019-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-01
  • 2020-12-02
  • 2018-08-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多