相关疑难解决方法(0)

如何将事件添加到使用VBA在Excel中运行时创建的控件

我想在运行时在Excel中使用VBA添加一个Control和一个关联的事件,但我不知道如何添加事件.

我尝试了下面的代码,并且在我的userform中正确创建了Button,但是应该显示hello消息的关联click事件不起作用.

任何建议/更正都会受到欢迎.

Dim Butn As CommandButton
Set Butn = UserForm1.Controls.Add("Forms.CommandButton.1")
With Butn
    .Name = "CommandButton1"
    .Caption = "Click me to get the Hello Message"
    .Width = 100
    .Top = 10
End With

With ThisWorkbook.VBProject.VBComponents("UserForm1.CommandButton1").CodeModule
    Line = .CountOfLines
    .InsertLines Line + 1, "Sub CommandButton1_Click()"
    .InsertLines Line + 2, "MsgBox ""Hello!"""
    .InsertLines Line + 3, "End Sub"
End With
UserForm1.Show
Run Code Online (Sandbox Code Playgroud)

events controls vba

15
推荐指数
3
解决办法
5万
查看次数

Excel VBA:如何将通用控件对象转换为ComboBox对象?

我需要将一个通用的VBA表单控件对象转换为一个ComboBox对象,以便我可以向它添加项目.通用对象不允许我将项目插入现有列表

Dim ctlCurrent As MSForms.Control
For Each ctlCurrent In frmItemInput.Controls
    If TypeName(ctlCurrent) = "ComboBox" Then
         Dim lbCurrentComboBox As MSForms.ComboBox
         lbCurrentComboBox = ctlCurrent 'This is where the error occurs, when I try to convert one into another

         ' Adiciona os itens necessários
         lbCurrentComboBox.AddItem ("R")
         lbCurrentComboBox.AddItem ("D")
    End If
Next ctlCurrent
Run Code Online (Sandbox Code Playgroud)

我的问题是:我的表单中有大量的ComboBox,我需要为它们添加相同的选项.所以我想这样做.

excel vba excel-vba

10
推荐指数
2
解决办法
2万
查看次数

处理在运行时创建的OLEObject CommandButtons的事件

我现在一直在努力解决这个问题......我想做一些非常简单的事情.我想在运行时创建多个命令按钮,然后使用一个过程处理这些命令按钮的事件.所以我构建了一个"withevents"类来处理自动化,但我的代码不起作用.当我运行Test()时,会创建CommandButton,但是当我点击它时...没有消息框响应......我找不到错误..请任何帮助都会很棒!!

类cTest

Public WithEvents Button As MSForms.CommandButton

Public Sub Button_Click()
s = MsgBox("Hello", vbOKOnly)
End Sub
Run Code Online (Sandbox Code Playgroud)

第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
Run Code Online (Sandbox Code Playgroud)

events vba ole event-handling commandbutton

4
推荐指数
1
解决办法
6404
查看次数

标签 统计

vba ×3

events ×2

commandbutton ×1

controls ×1

event-handling ×1

excel ×1

excel-vba ×1

ole ×1