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
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