Reputation: 21
Have a combobox & command button placed on excel sheet. Combobox will have some items listed, say it have 1, 2, 3, 4, 5. When the combobox is loaded for the first time, by default first value ie 1 will be selected.
Now using a VBA macro, I want to select next value from the combobox list (ie 2) and click on the command button.
I googled this but unfortunately, not getting what I am expecting.
Here is what I have so far, but it dont do what I am expecting (Explained above): Getting an error message as Object doesn't support this property or method on line If Worksheets("QC Update").ComboBox1.SelectedIndex < ComboBox1.Items.Count - 1 Then
Sub Select_Next_Items()
If IsEmpty(Range("A9").Value) = True Then
If Worksheets("QC Update").ComboBox1.SelectedIndex < ComboBox1.Items.Count - 1 Then
ComboBox1.ListIndex = 0 ' select first Item in listbox
ComboBox1.ListIndex = ComboBox1.ListCount - 1 ' selects last item
Set ComboBox1.SelectedIndex = Worksheets("QC Update").ComboBox1.SelectedIndex + 1
Set ComboBox1.ListCount = 0
End If
End If
End Sub
Upvotes: 1
Views: 7703
Reputation: 1
I share my simple solution
Try
ComboBoxDireccion.SelectedIndex = ComboBoxDireccion.SelectedIndex + 1
Catch ex As Exception
ComboBoxDireccion.SelectedIndex = 0
End Try
Upvotes: 0
Reputation: 69
hope you guys don't feel offended here, as I have a more clearer and a more straight forward answer.
ComboBox1.ListIndex = ComboBox1.ListIndex +1
Here is a more complete ones. We have to take into account when it is at the end of the list therefore
If ComboBox1.ListIndex = ComboBox1.ListCount -1 Then
ComboBox1.ListIndex =1
Else
ComboBox1.ListIndex = ComboBox1.ListIndex +1
I hope my reply is helpful to most of you especially those who are new to Vba and need to use it urgently.
This is simple to understand if you have solid background on programming in C++ / java
Upvotes: 3
Reputation: 21
Finally this issues is resolved with below code,
Set Cbx = Worksheets("QC Update").OLEObjects("ComboBox1")
With Cbx.Object
Ix = .ListIndex + 1
If Ix = .ListCount Then Ix = 0
If .ListCount Then .ListIndex = Ix
End With
Upvotes: 0
Reputation: 14373
I wonder if this is your intention.
Sub Select_Next_Item()
' 07 Apr 2017
Dim Ws As Worksheet
Dim Cbx As OLEObject
Dim Ix As Integer
Set Ws = Worksheets("QC Update")
If IsEmpty(Ws.Range("A9").Value) = True Then
Set Cbx = Ws.OLEObjects("ComboBox1")
With Cbx.Object
Ix = .ListIndex + 1
If Ix = .ListCount Then Ix = 0
If .ListCount Then .ListIndex = Ix
End With
End If
End Sub
If the cell A9 is found empty, the code will look at the "ComboBox1" (and will crash if it isn't found on the same, specified worksheet). It will change the selection in that combobox to the next value in the list. But if it was already at the last list item it will select the first, and if there are no list items in the combobox it will do nothing.
Upvotes: 0