我以前没有使用过列表框,在工作中也不需要经常使用对象,但不知为什么,我的代码对此运行正常。
ActiveSheet.ListBox1.AddItem MyName(i)
但如果我试图用工作表而不是ActiveSheet来获取列表框,它就会出错。
wkTest.ListBox1.AddItem MyName(i)
其中test是ListBox1所在的工作表。如果要根据listbox是的工作表来引用它,最好的方法是什么?还是这样做不对。
设置
Developers
点击 Insert
并在 ActiveX Controls
点击 List Box (ActiveX Control)
.Module1
).结论
ListBox
直呼其名 Shapes
和 OLEObjects collections
,两者都没有提供一个方法来添加项目到 ListBox
.CodeName
在代码的第二部分,通过各种解决方案来演示。法规
Option Explicit
Sub ListBoxTest()
' Worksheet
Dim wkTest As Worksheet: Set wkTest = ThisWorkbook.Worksheets("Sheet1")
' Shape - no use
Dim shTest As Shape: Set shTest = wkTest.Shapes("ListBox1")
Debug.Print "Shape", shTest.Name, shTest.Left
'shTest.AddItem "One" 'Run-time Error '438': Object doesn't support ...
' OLEObject - no use
Dim ooTest As OLEObject: Set ooTest = wkTest.OLEObjects("ListBox1")
Debug.Print "OLEObject", ooTest.Name, ooTest.Left
'ooTest.AddItem "One" 'Run-time Error '438': Object doesn't support ...
Dim obj As Object
'Set obj = wkTest.ListBox1 ' Compile error: Method or data member not found.
' Object 1 Solution
Set obj = Worksheets("Sheet1").ListBox1
Debug.Print "Object 1", obj.Name, obj.Left
obj.AddItem "One"
' Object 2 Solution
Set obj = Sheet1.ListBox1
Debug.Print "Object 2", obj.Name, obj.Left
obj.AddItem "Two"
' Object 3 Solution
wkTest.Activate
Set obj = ActiveSheet.ListBox1
Debug.Print "Object 3", obj.Name, obj.Left
obj.AddItem "Three"
' Favorite
With Sheet1.ListBox1
Debug.Print "Favorite", .Name, .Left
.AddItem "Four"
End With
End Sub
Sub ListBoxClear()
Dim obj As Object: Set obj = Worksheets("Sheet1").ListBox1
obj.Clear
End Sub