VBA:在工作表中初始化组合框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25207314/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VBA: Initialize Combo Box in worksheet
提问by Filippo
I have an error during initialization and I do not get why this is not working:
我在初始化期间出错,我不明白为什么这不起作用:
Private Sub Workbook_Open()
Dim ws As Worksheet
Set ws = Worksheets(1)
ws.ComboC15.AddItem "Technology"
end sub
It is very weird, the code should be correct. I have checked the combo name and it is "ComboC15".
很奇怪,代码应该是正确的。我检查了组合名称,它是“ComboC15”。
In fact, this is the sub:
事实上,这是子:
Private Sub ComboC15_Change()
Ps: I also checked the sheet and it is the first sheet where I have the Combo
Ps:我还检查了工作表,这是我拥有 Combo 的第一张工作表
采纳答案by djikay
The Worksheet
object in VBA doesn't have a property or method called ComboC15
, as this is entirely your own invention. However, the individual worksheetobject in your workbook, i.e. the sheet itself as a physical sheet and not as a VBA sheet, knows all about ComboC15
since it's been dropped on it by you. Therefore, you need to access the worksheet object (notice the little w) and not the Worksheet object (notice the big W). If it's confusing to read, imagine how confusing it is for me to try to explain this...
Worksheet
VBA 中的对象没有名为 的属性或方法ComboC15
,因为这完全是您自己的发明。但是,您的工作簿中的单个工作表对象,即作为物理工作表而不是 VBA工作表的工作表本身,ComboC15
因为它已被您放置在其上而了解所有信息。因此,您需要访问工作表对象(注意小w)而不是工作表对象(注意大W)。如果阅读令人困惑,想象一下我试图解释这一点是多么令人困惑......
To get access to the worksheet Object, you can do any of the following:
要访问工作表对象,您可以执行以下任一操作:
' Assuming "Sheet1" is the code name of the object. You can find this code name
' in the VBA editor. In the "Project Explorer" window, look under Microsoft
' Excel Objects. Your sheets are listed there in the form (for a blank, new
' workbook) "Sheet1 (Sheet1)". The bit *outside* the brackets is the code name.
Sheet1.ComboC15.AddItem "Technology"
' You can even call it directly from the "Worksheet" object by using the sheet
' index.
Worksheets(1).ComboC15.AddItem "Technology"
However, if you want to create a variable with it so you don't have to copy/paste the same thing over and over, declare it as an Object
and not as a Worksheet
. So do this:
但是,如果您想用它创建一个变量,这样您就不必一遍又一遍地复制/粘贴相同的内容,请将其声明为 anObject
而不是Worksheet
。所以这样做:
Private Sub Workbook_Open()
Dim ws As Object ' Declare ws as "Object"!
Set ws = Worksheets(1)
ws.ComboC15.AddItem "Technology"
End Sub
The following SO Q&A explains a bit more about the different kind of sheet names:
以下 SO Q&A 解释了有关不同类型工作表名称的更多信息:
and I hope this articlemight give you a better insight on how to reference different kinds of objects in VBA.
我希望这篇文章能让您更好地了解如何在 VBA 中引用不同类型的对象。