使用 VBA 重新创建具有 VBA 个事件的 ActiveX 控件
Recreating an ActiveX control with VBA events, using VBA
我有一个组合框,它绑定了多个事件(例如,ComboBox1_Change、Click、GotFocus、LostFocus)。出于我的目的,我需要使用 ActiveX 控件。
一些背景:
我 运行 遇到了一个问题,即当机器连接到投影仪时 ActiveX 控件出现故障。其他人遇到了同样的问题,但没有解决方案。我发现解决此问题的最佳方法是创建一个附加按钮,用户可以单击该按钮删除 ActiveX 控件并重新创建它。
问题是(也是我的问题)...当我这样做时,VBA 事件不再执行。该控件的名称完全相同。有没有简单的修复方法(比如我可以设置的ActiveX控件中的属性),这样我就不需要写VBA代码来删除和重写现有的VBA代码(我我什至不能 100% 肯定会解决问题)?
这似乎对我有用,在工作表中:
从工作表上的 2 个命令按钮开始:CommandButton1
和 CommandButton2
。
您无法单步执行代码,但它会 运行。
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
我有一个组合框,它绑定了多个事件(例如,ComboBox1_Change、Click、GotFocus、LostFocus)。出于我的目的,我需要使用 ActiveX 控件。
一些背景:
我 运行 遇到了一个问题,即当机器连接到投影仪时 ActiveX 控件出现故障。其他人遇到了同样的问题,但没有解决方案。我发现解决此问题的最佳方法是创建一个附加按钮,用户可以单击该按钮删除 ActiveX 控件并重新创建它。
问题是(也是我的问题)...当我这样做时,VBA 事件不再执行。该控件的名称完全相同。有没有简单的修复方法(比如我可以设置的ActiveX控件中的属性),这样我就不需要写VBA代码来删除和重写现有的VBA代码(我我什至不能 100% 肯定会解决问题)?
这似乎对我有用,在工作表中:
从工作表上的 2 个命令按钮开始:CommandButton1
和 CommandButton2
。
您无法单步执行代码,但它会 运行。
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