1

In the following

<select id="test">
 <option value="1">Test One</option>
 <option value="2">Test Two</option>
</select>

How can I get the text of the selected option (i.e. "Test One" or "Test Two") using VBA?

The exact same question was asked for JavaScript here: Retrieving the text of the selected <option> in <select> element

and the solution given was

function getSelectedText(elementId) {
    var elt = document.getElementById(elementId);

    if (elt.selectedIndex == -1)
        return null;

    return elt.options[elt.selectedIndex].text;
}

var text = getSelectedText('test');

I've created the following version in VBA, but I get an object doesn't support this property or method error at the if statement.

Function getSelectionText(SelectionObject)

If SelectionObject.selectedIndex = -1 Then getSelectionText = ""

getSelectionText = SelectionObject.Options(selection.selectedIndex).Text

End Function

There's to much code to post the call, but the function is definitely being passed a selection object.

Thanks for your help!

Community
  • 1
  • 1
ebrts
  • 361
  • 2
  • 7
  • 17

1 Answers1

1

Your function doesn't exit if selectedIndex is -1...

Function getSelectionText(SelectionObject)

If SelectionObject.selectedIndex = -1 Then 
    getSelectionText = ""
Else
    getSelectionText = SelectionObject.Options(SelectionObject.selectedIndex).Text
End If

End Function
Tim Williams
  • 154,628
  • 8
  • 97
  • 125
  • Thanks for the response that would have definitely broken the function further down the line, but I'm still getting the object doesn't support this property or method error on the if statement. It's like selectedIndex is not a property of the selection object when it should be. – ebrts Aug 05 '13 at 19:30
  • `selectedIndex` is definitely a valid property, so it seems likely the object being passed in is not what you think it is. If you put a watch on that variable what can you see? It might help to include the VBA where you're getting a reference to `SelectionObject` from your HTML. NOTE: there was also a typo in the `Else` part of your function which I corrected in my post. – Tim Williams Aug 05 '13 at 21:52