通过查询正确使用ListIndex导航表单

时间:2015-11-06 23:46:23

标签: vba ms-access

我有一个在组合框中有查询的子表单,我想浏览与查询结果匹配的不同记录。

在线,我找到了一个组合框的“ListIndex”函数,我的代码如下所示:“下一条记录”场景:

Private Sub Button_Click()
comboCountry.SetFocus
If comboCountry.ListIndex <> comboCountry.ListCount - 1 Then
        comboCountry.ListIndex = comboCountry.ListIndex + 1
Else
        comboCountry.ListIndex = 0
End If
End Sub

即使我的初始查询在组合框中输入有限数量的值,但当我按下按钮时,我会收到错误:Run-time error 7777; You've used the ListIndex property incorrectly

VBA调试器说错误的代码行是第4行,

comboCountry.ListIndex = comboCountry.ListIndex + 1

我的宏出了什么问题?

由于

2 个答案:

答案 0 :(得分:1)

嗯,在线帮助 - 您可以通过一键按下来访问 - 非常清楚:此属性是只读的

您可以这样做:

If comboCountry.ListIndex < comboCountry.ListCount - 1 Then
    comboCountry.Value = comboCountry.ItemData(comboCountry.ListIndex + 1)
End If

答案 1 :(得分:0)

我相信您错误代码的来源来自另一个网站(也许是字节?)。我不确定,但是我猜它在excel vba中与在access vba中有所不同。至少在ms Access vba中,listindex是只读的,并且combo.value = combo.itemdata(i)是用于设置选择的内容。

以下是用于使用箭头键在组合框列表项之间循环的代码。

Public Sub ArrowKeys(ByRef KeyCode As Integer, combo As ComboBox, ByRef Flag As Boolean)
' flag is used to be able to toggle normal action in combo_change()
Select Case KeyCode
    Case vbKeyDown
        KeyCode = 0 ' make sure the action wont be duplicated
        If combo.ListIndex <> combo.ListCount - 1 Then
          combo.Value = combo.ItemData(combo.ListIndex + 1)
          Flag = True
          combo.Dropdown
        Else
          combo.Value = combo.ItemData(0)
          Flag = True
          combo.Dropdown
        End If
   
   Case vbKeyUp
        KeyCode = 0 ' make sure the action wont be duplicated
        If combo.ListIndex = -1 Then ' In case nothingg is selected yet (-1 index)
          combo.Value = combo.ItemData(combo.ListCount - 1)
          combo.Dropdown
        ElseIf combo.ListIndex <> 0 Then
          combo.Value = combo.ItemData(combo.ListIndex - 1)
          Flag = True
          combo.Dropdown
        Else
          combo.Value = combo.ItemData(combo.ListCount - 1)
          Flag = True
          combo.Dropdown
        End If
End Select
End Sub
相关问题