Get Selected value of a Combobox Get Selected value of a Combobox vba vba

Get Selected value of a Combobox


You can use the below change event to which will trigger when the combobox value will change.

Private Sub ComboBox1_Change()'your code hereEnd Sub

Also you can get the selected value using below

ComboBox1.Value


If you're dealing with Data Validation lists, you can use the Worksheet_Change event. Right click on the sheet with the data validation and choose View Code. Then type in this:

Private Sub Worksheet_Change(ByVal Target As Range)    MsgBox Target.ValueEnd Sub

If you're dealing with ActiveX comboboxes, it's a little more complicated. You need to create a custom class module to hook up the events. First, create a class module named CComboEvent and put this code in it.

Public WithEvents Cbx As MSForms.ComboBoxPrivate Sub Cbx_Change()    MsgBox Cbx.ValueEnd Sub

Next, create another class module named CComboEvents. This will hold all of our CComboEvent instances and keep them in scope. Put this code in CComboEvents.

Private mcolComboEvents As CollectionPrivate Sub Class_Initialize()    Set mcolComboEvents = New CollectionEnd SubPrivate Sub Class_Terminate()    Set mcolComboEvents = NothingEnd SubPublic Sub Add(clsComboEvent As CComboEvent)    mcolComboEvents.Add clsComboEvent, clsComboEvent.Cbx.NameEnd Sub

Finally, create a standard module (not a class module). You'll need code to put all of your comboboxes into the class modules. You might put this in an Auto_Open procedure so it happens whenever the workbook is opened, but that's up to you.

You'll need a Public variable to hold an instance of CComboEvents. Making it Public will kepp it, and all of its children, in scope. You need them in scope so that the events are triggered. In the procedure, loop through all of the comboboxes, creating a new CComboEvent instance for each one, and adding that to CComboEvents.

Public gclsComboEvents As CComboEventsPublic Sub AddCombox()    Dim oleo As OLEObject    Dim clsComboEvent As CComboEvent    Set gclsComboEvents = New CComboEvents    For Each oleo In Sheet1.OLEObjects        If TypeName(oleo.Object) = "ComboBox" Then            Set clsComboEvent = New CComboEvent            Set clsComboEvent.Cbx = oleo.Object            gclsComboEvents.Add clsComboEvent        End If    Next oleoEnd Sub

Now, whenever a combobox is changed, the event will fire and, in this example, a message box will show.

You can see an example at https://www.dropbox.com/s/sfj4kyzolfy03qe/ComboboxEvents.xlsm


A simpler way to get the selected value from a ComboBox control is:

Private Sub myComboBox_Change()  msgbox "You selected: " + myComboBox.SelTextEnd Sub