MS Access多控件KeyPress CTRL + A处理程序 [英] MS Access Multi-control KeyPress CTRL+A Handler
问题描述
我有一个包含10多个文本控件的Access数据库.我想要一些代码来处理CTRL + KeyPress事件.通常,在Access中按CTRL + A时,这会选择所有记录.我的最终目标是让CTRL + A只选择该控件的文本(就像在浏览器的URL栏中按CTRL + A一样,它只选择该文本),这样我就只能删除该控件的文本.我检查了这篇文章,我想要可以处理任何文本框的东西(处理每个文本框的KeyPress = 60行以上的代码).我有什么办法可以说一个for-next循环吗?
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?
注意:如果您还没有注意到,我仍然是使用VBA/Access的菜鸟.
Note: In case you haven't noticed yet, I'm still a noob with VBA/Access.
推荐答案
您当前的方法将不起作用,因为它包含多种在VBA中无法正常工作的内容(如June7所述),并且由于表单按键事件优先于文本框按键事件
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
您可以改用以下代码(受 SU上的答案启发)
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
使用VBA或仅使用属性窗格将Form.KeyPreview
属性设置为True,这一点很重要,以使此功能比默认行为具有优先权.
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.
这篇关于MS Access多控件KeyPress CTRL + A处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!