MS Access Multi-control KeyPress CTRL+A Handler

六月ゝ 毕业季﹏ 提交于 2019-11-30 06:00:04

问题


I have an Access database with 10+ text controls. I'd like to have some code to handle the CTRL + A KeyPress event. Normally, when pressing CTRL + A in Access, this selects all records. My end goal is to have CTRL + A only select that control's text (like pressing CTRL + A in your browser's URL bar, it only selects THAT text) so that I can delete only that control's text. I checked this article, as I wanted something that could handle any text box (handling each textbox's KeyPress = 60+ lines of code). Is there any way I could have, say, a for-next loop?

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

Along with this, how can I pass to this sub/function the text box's name?

Note: In case you haven't noticed yet, I'm still a noob with VBA/Access.


回答1:


Your current approach will not work, since it contains multiple things that just don't work that way in VBA (as June7 noted), and since form keydown events take priority over textbox keydown events

You can use the following code instead (inspired by 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

It's important to set the Form.KeyPreview property to True, either using VBA or just the property pane, to allow this function to take priority over the default behaviour.



来源:https://stackoverflow.com/questions/47735162/ms-access-multi-control-keypress-ctrla-handler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!