简体   繁体   English

如何在Excel 2016 VBA中引用ActiveX ComboBox

[英]How to reference ActiveX ComboBox in Excel 2016 VBA

I've tried various solutions on here and elsewhere such as: 我在这里和其他地方尝试了各种解决方案,例如:

dim wb as workbook, ws as worksheet

Dim cb As Object
Set cb = ws.OLEObjects("ComboBoxViews")

or 要么

ComboBoxViews

or 要么

ws.comboboxviews

But all return Error 1004, the item with specified name wasn't found. 但是全部返回错误1004,未找到具有指定名称的项目。 But it DOES exist, checking properties the name is very clearly 'comboboxviews'. 但是它确实存在,检查属性的名称很明显是'comboboxviews'。

Any ideas? 有任何想法吗?

EDIT: 编辑:

To make it clear for anyone else seeking help in the future and using Romcel's very helpful code as a base, it seems that in order to add items to an ActiveX ComboBox (which is my final goal), you need to reference it as an object: 为了使以后寻求帮助并使用Romcel的非常有用的代码作为基础的其他人更加清楚,似乎要将项目添加到ActiveX ComboBox(这是我的最终目标),您需要将其作为对象引用:

Sub caller3()
Dim ws As Worksheet
Dim oleob As OLEObject
Set ws = ThisWorkbook.Sheets("Sheet1")

For Each oleob In ws.OLEObjects
  If TypeName(oleob.Object) = "ComboBox" Then
    oleOb.Object.AddItem "TEST"  <<< CORRECT
    oleOb.AddItem "TEST"  <<< INCORRECT
  End If
Next

End Sub

You can bluntly refer to your controls in the worksheet like. 您可以像在工作表中那样直截了当地引用您的控件。

Sub caller1a()
Sheet1.ComboBox1.Value = "value 1a"    '   no errors
End Sub


But you cannot referto them like this. 但是您不能像这样引用它们。

Sub caller1b()
Dim ws As Worksheet
  Set ws = Sheet1
  ws.ComboBox1.Value = "value1b"    '  will give error
End Sub


If you are familiar with how Excel gives each control their respective index. 如果您熟悉Excel如何为每个控件提供各自的索引。 You can refer to each control as. 您可以将每个控件称为。

Sub caller2()
Dim ws As Worksheet
  Set ws = Sheet1
  ws.OLEObjects(1).Object.Value = "value2"
End Sub

Or just safely loop through them and check if it is the right control you are working with. 或者只是安全地遍历它们,并检查它是否是您使用的正确控件。

Sub caller3()
Dim ws As Worksheet
Dim oleob As OLEObject
Set ws = ThisWorkbook.Sheets("Sheet1")

For Each oleob In ws.OLEObjects
  If TypeName(oleob.Object) = "ComboBox" Then
    oleob.Object.Value = "value3"
  End If
Next

End Sub

Hope this helps. 希望这可以帮助。 Good luck! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM