当组合框具有焦点时显示下拉列表

时间:2019-01-01 18:07:26

标签: vba ms-access combobox access-vba

是否可以在Access表单上放一点代码,以便只要表单上的任何组合框都具有焦点,它就会自动显示下拉列表?

我知道只要组合框具有焦点,就可以使用以下事件自动显示下拉列表。但是,如果可能的话,我希望不必在每个组合框上都放这行代码,因为我有那么多。

Private Sub combobox_GotFocus()
    'When the combobox receives focus
    'display in drop down position
    Me.combobox.Dropdown
End Sub

我的数据库中包含数十种表单,每种表单上都有许多组合框。

1 个答案:

答案 0 :(得分:0)

创建一个名为cComboBox的类

Option Compare Database
Option Explicit

Private WithEvents mComboBox As Access.ComboBox

Private Sub mComboBox_GotFocus()
    mComboBox.Dropdown
End Sub

Public Function AddCtl(nCtl As Access.ComboBox) As Access.ComboBox
    Set mComboBox = nCtl
    mComboBox.OnGotFocus = "[Event Procedure]"
    'mComboBox.OnChange = "[Event Procedure]"
    Set AddCtl = mComboBox
End Function

并将以下代码添加到您的表单

Option Compare Database
Option Explicit

Dim myCBs As New Collection

Private Sub Form_Load()
Dim myCB As cComboBox

Dim ctl As Access.Control
    For Each ctl In Me.Controls
        If TypeName(ctl) = "ComboBox" Then
            Set myCB = New cComboBox
            myCB.AddCtl ctl
            myCBs.Add myCB
        End If
    Next

End Sub