Reputation: 113
I found a solution that will allow me to use Ctrl+A combo in an Access textbox in order to select all of the text inside it.
This solution needs:
Form.KeyPreview
property to True
Form.Keydown
: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
I tried to put this code in a module like this:
Public Sub CtrlA(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
In order to call it wherever I want like this:
Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
Call CtrlA(KeyCode, Shift)
End Sub
But the Me
keyword isn't allowed in a standard module.
How can I achive this goal?
Upvotes: 0
Views: 1076
Reputation: 3465
Following your code sample this is what you want:
You have to forward the control (here it is named text0
) to your procedure.
The argument KeyCode
must be defined ByRef
to be able to return the value 0
to the calling procedure.
Call it like this from in a form:
Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
Call CtrlA(Text0, KeyCode, Shift)
End Sub
In a module:
Public Sub CtrlA(ByVal contextControl As Control, ByRef KeyCode As Integer, ByVal 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 contextControl Is TextBox Then
With contextControl
.SelStart = 0
.SelLength = Len(.Text)
End With
End If
End If
ExitSub:
End Sub
Following Andres suggestion (thx to him) to pass the form itself, you can do it like this:
Call it like this from in a form:
Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
Call CtrlA(Me, KeyCode, Shift)
End Sub
In a module:
Public Sub CtrlA(ByVal contextForm As Form, ByRef KeyCode As Integer, ByVal 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 contextForm.ActiveControl Is TextBox Then
With contextForm.ActiveControl
.SelStart = 0
.SelLength = Len(.Text)
End With
End If
End If
ExitSub:
End Sub
Upvotes: 3