无法引用工作表上的列表框

问题描述 投票:1回答:1

我以前没有使用过列表框,在工作中也不需要经常使用对象,但不知为什么,我的代码对此运行正常。

ActiveSheet.ListBox1.AddItem MyName(i)

但如果我试图用工作表而不是ActiveSheet来获取列表框,它就会出错。

wkTest.ListBox1.AddItem MyName(i)

其中test是ListBox1所在的工作表。如果要根据listbox是的工作表来引用它,最好的方法是什么?还是这样做不对。

excel vba listbox
1个回答
0
投票

列表框ActiveX控件的缺点?

设置

  • 打开一个新的工作表,在 Developers 点击 Insert并在 ActiveX Controls 点击 List Box (ActiveX Control).
  • 将控件 "绘制 "到工作表上。将以下代码复制到一个标准的模块中(如 Module1).

结论

  • 代码的第一部分演示了虽然你可以访问到 ListBox 直呼其名 ShapesOLEObjects 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
© www.soinside.com 2019 - 2024. All rights reserved.