Return the text from a dropdown box rather than the index number

后端 未结 2 757
死守一世寂寞
死守一世寂寞 2021-01-14 10:02

I have the following VBA code (from MS Access 2007). The code creates a new workbook and adds a dropdown to a cell. This small snippet adds a drop down to a particular cell

2条回答
  •  無奈伤痛
    2021-01-14 10:26

    I was trying to find a neater way of doing this so might as well ressurect this question :) Here's how I have been solving this problem. I create an array of the items I want to fill the drop down with. Then using this array you can return the string associated with the index you get from the drop down.

    First create a function to return an array of strings:

    ' Returns a string array of drop down items
    function dditems() as string()
    
        Dim array(2) As String
    
        array(1) = "cats"
        array(2) = "dogs"
    
        dditems = array
    
    end function
    

    Then use this array to populate your drop down:

    ' To populate your drop down
    sub populatedd()
    
        dim dd As DropDown
        dim i As Integer 
        dim itemsArray() As String
    
        ' Create the dd object and item array
        set dd = Worksheets("Sheet1").DropDowns("Drop Down 1")
        set itemsArray = dditems()
    
        ' Loop through the array to populate the drop down
        for i = 1 to UBound(itemsArray)
    
            dd.AddItem (itemsArray(i))
    
        next i
    end
    

    Then by using this array again you can use the following code to get the string associate with the drop down index selected:

    ' Get the string associated with the index
    sub showDDResult()
    
        dim dd As DropDown
        dim itemsArray() As String
    
        ' Create the dd object and item array
        set dd = Worksheets("Sheet1").DropDowns("Drop Down 1")
        set itemsArray = dditems()
    
        ' dd.ListIndex returns index, call to array returns correct string
        MsgBox("Item selected is " & itemsArray(dd.ListIndex))
    end
    

提交回复
热议问题