有一个组合框&放在Excel工作表上的命令按钮。 Combobox会列出一些项目,比如它有1,2,3,4,5。当第一次加载组合框时,默认情况下会选择第一个值,即1。
现在使用VBA宏,我想从组合框列表中选择下一个值(即2),然后单击命令按钮。
我用谷歌搜索了这个,但不幸的是,没有得到我所期待的。
这是我到目前为止所做的,但它没有做我期待的事情(上面解释):获取错误消息作为对象不支持此属性或方法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
答案 0 :(得分:2)
希望你们在这里感到被冒犯,因为我有更清晰,更直接的答案。
ComboBox1.ListIndex = ComboBox1.ListIndex +1
这是一个更完整的。因此,我们必须考虑到列表末尾的时间
If ComboBox1.ListIndex = ComboBox1.ListCount -1 Then
ComboBox1.ListIndex =1
Else
ComboBox1.ListIndex = ComboBox1.ListIndex +1
我希望我的回复对大多数人有帮助,尤其是那些刚接触Vba并需要紧急使用它的人。
如果您具有使用C ++ / java
编程的扎实背景,这很容易理解答案 1 :(得分:0)
我想知道这是不是你的意图。
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
如果发现单元格A9为空,则代码将查看“ComboBox1”(如果在同一个指定的工作表中找不到它,则会崩溃)。它会将组合框中的选择更改为列表中的下一个值。但如果它已经在最后一个列表项中,它将选择第一个,如果组合框中没有列表项,它将什么都不做。
答案 2 :(得分:0)
最后,使用以下代码
解决了这个问题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
答案 3 :(得分:0)
我分享我的简单解决方案
Try
ComboBoxDireccion.SelectedIndex = ComboBoxDireccion.SelectedIndex + 1
Catch ex As Exception
ComboBoxDireccion.SelectedIndex = 0
End Try