gpt4 book ai didi

events - 处理运行时创建的 OLEObject 命令按钮的事件

转载 作者:行者123 更新时间:2023-12-02 20:32:09 26 4
gpt4 key购买 nike

我已经为这个问题苦苦挣扎了一段时间......我想做一些非常简单的事情。我想在运行时创建多个命令按钮,然后用一个过程处理这些命令按钮的事件。所以我构建了一个“withevents”类来处理自动化,但我的代码不起作用。当我运行 Test() 时,会创建 CommandButton,但是当我单击它时...没有消息框响应...我找不到错误...请提供任何帮助!!

cTest 类

Public WithEvents Button As MSForms.CommandButton

Public Sub Button_Click()
s = MsgBox("Hello", vbOKOnly)
End Sub

模块 1

Public TestCollection As Collection

Sub Test()

Set TestCollection = New Collection
Dim Btn As CommandButton
Dim OLEBtnObj As cTest
Set OLEBtnObj = New cTest
Set Btn = Sheet1.OLEObjects.Add(ClassType:="Forms.CommandButton.1", link:=False,_ DisplayAsIcon:=False, Left:=368.25, Top:=51, Width:=44.25, Height:=24).Object
Set OLEBtnObj.Button = Btn
TestCollection.Add Item:=OLEBtnObj

End Sub

最佳答案

我有一个相当不切实际的解决方案。要测试它,请将以下代码放入工作表类模块中(参见附图)。 Me.CodeName 引用 Code-Name工作表的。

对于每个新的 Sheet1 按钮,都会添加一个新处理的事件。此事件处理程序将执行公共(public)事件处理程序并将单击的命令按钮的名称传递给它。

' Standard Module
Sub test()
' adds three buttons to Sheet1 with click-event handlers
Sheet1.AddButton
ActiveCell.Offset(5, 0).Activate
Sheet1.AddButton
ActiveCell.Offset(5, 0).Activate
Sheet1.AddButton
End Sub

' Sheet1 Class Module
Option Explicit

' Add Microsoft Visual Basic For Applications Extensibility

Public Function AddButton() As MSForms.CommandButton
Dim msFormsCommandButton As MSForms.CommandButton
Set msFormsCommandButton = Me.OLEObjects.Add(ClassType:="Forms.CommandButton.1").Object
CreateEventHandler msFormsCommandButton.Name
Set AddButton = msFormsCommandButton
End Function

Private Sub CommonButton_Click(ByVal buttonName As String)
MsgBox "You clicked button [" & buttonName & "]"
End Sub

Private Sub CreateEventHandler(ByVal buttonName As String)
Dim VBComp As VBIDE.VBComponent
Dim CodeMod As VBIDE.CodeModule
Dim codeText As String
Dim LineNum As Long

Set VBComp = ThisWorkbook.VBProject.VBComponents(Me.CodeName)
Set CodeMod = VBComp.CodeModule
LineNum = CodeMod.CountOfLines + 1

codeText = codeText & "Private Sub " & buttonName & "_Click()" & vbCrLf
codeText = codeText & " Dim buttonName As String" & vbCrLf
codeText = codeText & " buttonName = """ & buttonName & "" & vbCrLf
codeText = codeText & " CommonButton_Click buttonName" & vbCrLf
codeText = codeText & "End Sub"
CodeMod.InsertLines LineNum, codeText
End Sub
<小时/>

enter image description here

关于events - 处理运行时创建的 OLEObject 命令按钮的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14994235/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com