我想做的事与this post给出的答案非常相似。唯一的区别是我想将OLEObject添加到用户表单,而不是工作表。
编辑1 :我尝试了SELECT ProductName,
MAX(CASE
WHEN Branch=1
THEN Status
ELSE NULL
END) AS 'Branch 1',
MAX(CASE
WHEN Branch=2
THEN Status
ELSE NULL
END) AS 'Branch 2'
FROM MyTable
GROUP BY ProductName;
编辑2 :我在这里发布了整个代码:
UserForm1.OLEObjects.Add("Forms.ComboBox.1")

编辑3 :这是类代码:
'this is public so it doesn't go out of scope
Public gclsControlEvents As CControlEvents
Sub Bouton1_Click()
Call MakeCombo
End Sub
Sub MakeCombo()
Dim oleCbx As OLEObject
'Create the combobox
Set oleCbx = UserForm1.Controls.Add("Forms.ComboBox.1") 'Bug at this line
oleCbx.Object.AddItem "1"
oleCbx.Object.AddItem "2"
'hookup the events
Application.OnTime Now, "HookupEvents"
End Sub
Sub HookupEvents()
Set gclsControlEvents = New CControlEvents
Set gclsControlEvents.Cbx = UserForm1.OLEObjects(1).Object
End Sub
答案 0 :(得分:2)
您需要将OLEObjects
的所有引用替换为Controls
,变量类型为MSForms.Control
而不是OLEObject
,因此:
Sub MakeCombo()
Dim oleCbx As MSForms.Control
'Create the combobox
Set oleCbx = UserForm1.Controls.Add("Forms.ComboBox.1")
oleCbx.AddItem "1"
oleCbx.AddItem "2"
'hookup the events
Application.OnTime Now, "HookupEvents"
End Sub
我没有查找类代码,但这需要进行类似的更改。
对于用户表单,不需要OnTime
,因为项目没有重置,并且您的变量不会超出范围。你需要的只是类,然后在userform本身你可以放这样的东西:
Option Explicit
'this is public so it doesn't go out of scope
Public gclsControlEvents As CControlEvents
Private Sub UserForm_Initialize()
Dim oleCbx As MSForms.ComboBox
'Create the combobox
Set oleCbx = Me.Controls.Add("Forms.ComboBox.1") 'Bug at this line
oleCbx.AddItem "1"
oleCbx.AddItem "2"
Set gclsControlEvents = New CControlEvents
Set gclsControlEvents.Cbx = oleCbx
End Sub
不需要其他代码。
答案 1 :(得分:0)
我不太了解这个问题,但这应该运行(未经测试)
Sub MakeCombo()
'Create the combobox
Set oleCbx = UserForm1.Controls.Add("Forms.ComboBox.1")
oleCbx.Object.AddItem "1"
oleCbx.Object.AddItem "2"
'hookup the events
Application.OnTime Now, "HookupEvents"
End Sub