【问题标题】:How to navigate in a ListBox by VBA code?如何通过 VBA 代码在 ListBox 中导航?
【发布时间】:2018-10-10 16:44:16
【问题描述】:

我想在访问表单中插入一些导航按钮。用户应该能够使用此按钮在 ListBox 中上下导航。 ListBox 不可多选。

这是我上一个按钮的代码:

Private Sub btnPrev_Click()
    myListBox.SetFocus
    myListBox.ListIndex = MyLib.max(0, myListBox.ListIndex - 1)
    btnPrev.SetFocus
End Sub

代码问题:

  1. 我必须将焦点设置到 ListBox。如果不是,我会收到错误 7777(属性 ListIndex 的错误使用)
  2. ListBox 必须处于活动状态,因为如果不活动,SetFocus 将无法工作。
  3. 不能锁定列表框

在 ListBox 中使用 vba 导航的最佳做法是什么?

【问题讨论】:

    标签: ms-access


    【解决方案1】:

    您不应该使用.ListIndex 属性来移动。

    改用.ItemsSelected.Selected

    Private Sub btnPrev_Click()
        With myListBox
            If .ItemsSelected.Count = 0 Then Exit Sub 'Can't move to previous if nothing is selected
            Dim currentPosition As Long
            currentPosition = .ItemsSelected(0) 'Current position = position of first selected item
            If currentPosition = 0 Then Exit Sub 'Can't move lower than 0
            .Selected(currentPosition) = False 'Deselect current item
            .Selected(currentPosition-1) = True 'Select previous item
        End With
    End Sub
    

    当列表框不是多选时,可以省略取消选择当前项目,因为在这种情况下选择一个项目会取消选择所有其他项目。

    【讨论】:

    • 效果很好,谢谢。唯一的问题(对我来说)是当所选记录发生变化时,我必须过度思考我的逻辑。表格也应该切换到该记录。到目前为止,我一直在使用 click-event,但它不再被触发了。
    • Eh... 只需致电 sub:myListbox_ClickCall myListbox_Click()。但是,在没有事件的情况下调用事件处理程序是一种糟糕的设计实践,您应该有一个单独的子程序来移动记录,并在需要时调用它(在事件处理程序中,在此子程序的末尾)。
    • 是的,我会在按钮代码末尾和点击事件中调用“updateFormData”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多