I’ve seen this question a few times over the years:
How can I set the focus on the next control on a form as if the user pressed the tab button?
Now there are a variety of possible answers
SendKeys
I cringe to say it, but SendKeys can be a solution, but at the same time SendKeys are notorious for causing issues and are to be avoided at all cost. Never the less, you could simply do something like
SendKeys "{tab}"
User Defined Function
Per the usual, the best solution is to create your own function to do the job! Below is one such function
'---------------------------------------------------------------------------------------
' Procedure : GotoNextTabIndexCtrl
' Author : Daniel Pineault, CARDA Consultants Inc.
' Website : http://www.cardaconsultants.com
' Purpose : Move the focus to the next control on a form per the TabIndex numbering
' Copyright : The following is release as Attribution-ShareAlike 4.0 International
' (CC BY-SA 4.0) - https://creativecommons.org/licenses/by-sa/4.0/
' Req'd Refs: None required
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' ActiveCtrl - The current control from which you wish to move to the next control from
'
' Usage:
' ~~~~~~
' Call GotoNextTabIndexCtrl(Me.FirstName)
' Call GotoNextTabIndexCtrl(ActiveControl)
'
' Revision History:
' Rev Date(yyyy/mm/dd) Description
' **************************************************************************************
' 1 2015-03-22 Initial Release
' 2 2018-05-27 Added Visible check
' 3 2019-08-07 Initial Public Release
'---------------------------------------------------------------------------------------
Public Sub GotoNextTabIndexCtrl(ActiveCtrl As Access.Control)
Dim Ctrl As Access.Control
Dim iTabIndex As Integer
On Error GoTo Error_Handler
iTabIndex = ActiveCtrl.TabIndex
StartOver:
For Each Ctrl In ActiveCtrl.Parent
Select Case Ctrl.ControlType
Case acCheckBox, acComboBox, acCommandButton, acListBox, _
acOptionGroup, acTextBox, acWebBrowser
If Ctrl.TabStop = True Then
If Ctrl.TabIndex = iTabIndex + 1 Then
If Ctrl.Visible = False Then
iTabIndex = iTabIndex + 1
GoTo StartOver
Else
Ctrl.SetFocus
Exit For
End If
End If
End If
End Select
Next Ctrl
Error_Handler_Exit:
On Error Resume Next
If Not Ctrl Is Nothing Then Set Ctrl = Nothing
Exit Sub
Error_Handler:
MsgBox "The following error has occurred" & vbCrLf & vbCrLf & _
"Error Number: " & Err.Number & vbCrLf & _
"Error Source: GotoNextTabIndexCtrl" & vbCrLf & _
"Error Description: " & Err.Description & _
Switch(Erl = 0, "", Erl <> 0, vbCrLf & "Line No: " & Erl) _
, vbOKOnly + vbCritical, "An Error has Occurred!"
Resume Error_Handler_Exit
End Sub
Hopefully the above will help a few of you out there.
I have controls in both the header and the detail sections of a form. While this works as designed, if an active control is in the detail section it moves to the next (numerical) control in the header instead of the same section.