如何使用 activex 控件动态填充 excel 工作表?



我有一个要求,我必须在工作表上动态放置 activex 控件,因为有太多控件要放在用户窗体上。

我已经找到了一种方法来做到这一点:

Worksheets(1).OLEObjects.Add ClassType:="Forms.ListBox.1"

但是如何将函数/宏分配给与该控件关联的各种事件。例如。如果我在运行时动态插入旋转按钮,如何对其事件进行编程。

下面是一个示例:

Option Explicit
Public Sub test()
MsgBox "Hello"
End Sub
Public Sub AddWorksheetEventCode()
'Tools > references > Microsoft Visual Basic for Applications Extensibility 5.3
'Trust access to VBA model
Dim wb As Workbook
Dim wsNew As Worksheet
Set wb = ThisWorkbook
Dim xPro As VBIDE.VBProject
Dim xCom As VBIDE.VBComponent
Dim xMod As VBIDE.CodeModule
Dim xLine As Long
Set wsNew = wb.Worksheets("Sheet1")
With wsNew
.OLEObjects.Add ClassType:="Forms.CommandButton.1", _
Link:=False, DisplayAsIcon:=False, Left:=40, Top:=40, _
Width:=150, Height:=20
'<==== This section adds the event to the project
Set xPro = wb.VBProject
Set xCom = xPro.VBComponents("Sheet1") '<== Defining the location to add
Set xMod = xCom.CodeModule
With xMod
xLine = .CreateEventProc("Click", "CommandButton1") '<== Defining the event to add
xLine = xLine + 1
.InsertLines xLine, "test" '<== Defining the text within the event code i.e. calling the sub
End With
End With
End Sub

在上面,我在一个名为test的标准模块中有现有的过程。这是我将与命令按钮关联的子(宏(。


目标:

根据你的问题,据我了解,你想

  1. 以编程方式添加 ActiveX 对象
  2. 以编程方式向此对象添加事件

1.添加对象

.OLEObjects.Add部分添加命令按钮。


2. 添加事件

Set xPro = wb.VBProject向下的部分是构造事件(命令按钮单击(并使用调用子test的命令填充该事件。VBIDE 是以编程方式交互以创建项目组件(如事件(的方式。

VBIDE 是定义所有对象和 构成 VBProject 和 Visual Basic 编辑器的值。

a.定义要添加的位置

Set xCom = xPro.VBComponents("Sheet1")

b.定义要添加的事件

xLine = .CreateEventProc("Click", "CommandButton1")

c.定义事件代码中的文本,即调用 sub

.InsertLines xLine, "test" 

编辑:

更好的办法是定义一个类来处理所有这些问题。在那里定义方法等。


设置对象属性的示例;首先,在添加时将对象放入变量中,然后在以后使用其属性时引用该变量,例如

Dim b As Object
With wsNew
Set b = .OLEObjects.Add(ClassType:="Forms.CommandButton.1", _
Link:=False, DisplayAsIcon:=False, Left:=40, Top:=40, _
Width:=150, Height:=20)
Set xPro = wb.VBProject
Set xCom = xPro.VBComponents("Sheet1")
Set xMod = xCom.CodeModule
With xMod
xLine = .CreateEventProc("Click", "CommandButton1")
xLine = xLine + 1
.InsertLines xLine, "test"
End With
End With
b.Height = 150

警告:

抓住@MathieuGuindon提出的要点 - 这种元编程容易出错,您将无法简单地调试。

相关内容

最新更新