How do I refer to a controls object, on a worksheet, using a variable name?

后端 未结 4 1913
慢半拍i
慢半拍i 2021-01-11 20:06

I have added a ListBox to a SHEET (not to a \"UserForm\") I did this using the mouse. I clicked the little Hammer and Wrench icon.

This ListBox seems to be easily re

相关标签:
4条回答
  • 2021-01-11 20:35

    Try this:

    Dim cMyListbox As MSForms.ListBox
    
    Set cMyListbox = Sheet1.ListBox1  '// OR Worksheets("YourSheetName").Listbox1
    
    cMyListbox.AddItem("An option")
    

    Also you can populate a listbox without having to loop through the array, try this:

    Dim cMyListbox As MSForms.ListBox
    Dim vArray As Variant
    
    Set cMyListbox = Sheet1.ListBox1
    
    vArray = Range("A1:A6").Value
    cMyListbox.List = vArray
    
    0 讨论(0)
  • 2021-01-11 20:42

    Change the sub signature to match this:

    Sub populate_listbox(LB As MSForms.ListBox, dataArray As Variant)

    Now you can pass it like you were trying to originally.

    NOTE: This only works if you used the "ActiveX" version of the listbox. I'm assuming you are because you are able to call ListBox1 straight from a module.

    PS: The ActiveX controls are members off of the parent sheet object. So if you have the listbox1 on sheet1, you can also call it like Sheet1.ListBox1 so you don't get confused if you end up with multiple sheets with multiple listboxes. Also, you may want to change the name just to make it easier on yourself.

    0 讨论(0)
  • 2021-01-11 20:44
    Dim controlName As OLEObject
        Set controlName = Sheet1.OLEObjects("ListBox1")
    
    Call populate_listbox(controlName, designAreaArray)
    
    Sub populate_listbox(LB As OLEObject, dataArray As Variant)
        Dim i As Integer: i = 0
        For i = LBound(dataArray, 2) + 1 To UBound(dataArray, 2)    ' Skip header row
           LB.Object.AddItem (dataArray(Index, i))
        Next i
    End Sub
    
    0 讨论(0)
  • 2021-01-11 20:47

    To access the state of a checkbox Active-X control on Sheet1:

    Dim checkBox1 As Object
    Set checkBox1 = Sheet1.OLEObjects("CheckBox1").Object
    MsgBox checkBox1.Value
    
    0 讨论(0)
提交回复
热议问题