MS Access 多控制 KeyPress CTRL+A 处理程序 [英] MS Access Multi-control KeyPress CTRL+A Handler
问题描述
我有一个包含 10 多个文本控件的 Access 数据库.我想要一些代码来处理 CTRL + A 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 所指出的),并且由于形成 keydown 事件优先于文本框按键事件
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
将 Form.KeyPreview
属性设置为 True 很重要,无论是使用 VBA 还是仅使用属性窗格,以允许此函数优先于默认行为.
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屋!