MS Access 多控制按键 CTRL+A Handler

MS Access Multi-control KeyPress CTRL+A Handler

我有一个包含 10 多个文本控件的 Access 数据库。我想要一些代码来处理 CTRL + A KeyPress 事件。通常,在Access中按CTRL + A时,这selects all记录。我的最终目标是让 CTRL + A 只有 select 控件的文本(就像在浏览器的 URL 栏中按 CTRL + A,它只有 select 那个文本)这样我就可以删除只有该控件的文本。我检查了 this article,因为我想要可以处理任何文本框的东西(处理每个文本框的 KeyPress = 60+ 行代码)。有什么办法可以让我有一个 for-next 循环吗?

Function HandleKeyPress(frm As Form, KeyAscii As Integer, ByVal e As KeyPressEventArgs) 'should it be a function or a sub?
    For Each ctl In Me.Controls
        If KeyAscii = 1 Then    'I think this is CTRL + A?
            e.Handled = True    'Stop this keypress from doing anything in access
            focused_text_box.SelStart = 0
            focused_text_box.SelLength = Len(focused_text_box.Text)
        End If
    Next
End Function

除此之外,我如何传递给这个 sub/function 文本框的名称?

注意:如果你还没有注意到,我仍然是 VBA/Access 的菜鸟。

您当前的方法行不通,因为它包含多个在 VBA 中不起作用的东西(如 June7 所述),并且由于表单按键事件优先于文本框按键事件

您可以改用以下代码(受this answer on SU启发):

Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
    If KeyCode = vbKeyA And Shift = acCtrlMask Then 'Catch Ctrl+A
        KeyCode = 0 'Suppress normal effect
        On Error GoTo ExitSub 'ActiveControl causes a runtime error if none is active
        If TypeOf Me.ActiveControl Is TextBox Then
            With Me.ActiveControl
                .SelStart = 0
                .SelLength = Len(.Text)
            End With
        End If
    End If
ExitSub:
End Sub

重要的是将 Form.KeyPreview 属性 设置为 True,使用 VBA 或只使用 属性 窗格,以允许此功能优先于默认设置行为。