Introduction
When using a VBA UserForm to input dates or times, users often have to type numbers in a sequence like “Year -> Month -> Day -> Hour -> Minute -> Second.” Pressing the Tab key after every single entry can be tedious and slow down the process.
In this article, I will introduce a method to automatically move the focus to the next TextBox as soon as the text reaches the maximum character limit (MaxLength). This is easy for beginners to implement and will significantly improve the data entry efficiency of your forms.
Overview: How It Works
The mechanism is simple. We use the Change event of each TextBox to check if the current number of characters has reached the MaxLength. If it has, the code automatically moves the focus to the next specified TextBox.
Prerequisites
Before writing the code, you need to set the MaxLength property for each TextBox in the Properties window of the Visual Basic Editor.
Example Settings:
- Year: 4
- Month, Day, Hour, Minute, Second: 2
Sample Code (UserForm Module)
Below is an implementation example. You can change the control names to match your project. The logic is set up to move focus in the order of “Input Field -> Next Field.”
' Common procedure: Move to the next TextBox when the max length is reached
Private Sub JumpToNextBox(currentBox As MSForms.TextBox, nextBox As MSForms.TextBox)
If Len(currentBox.Text) >= currentBox.MaxLength Then
nextBox.SetFocus
End If
End Sub
' Call the common procedure from the Change event of each TextBox
Private Sub txtYear_Change()
JumpToNextBox txtYear, txtMonth
End Sub
Private Sub txtMonth_Change()
JumpToNextBox txtMonth, txtDay
End Sub
Private Sub txtDay_Change()
JumpToNextBox txtDay, txtHour
End Sub
Private Sub txtHour_Change()
JumpToNextBox txtHour, txtMinute
End Sub
Private Sub txtMinute_Change()
JumpToNextBox txtMinute, txtSecond
End Sub
' For the final field (Seconds), move focus to a command button (optional)
Private Sub txtSecond_Change()
If Len(txtSecond.Text) >= txtSecond.MaxLength Then
btnSubmit.SetFocus
End If
End Sub
Implementation Notes
- BackSpace: Focus will not move if you delete characters using the BackSpace key. This is intentional to allow for corrections.
- Custom Order: If you want to change the input order, simply change the arguments passed to
JumpToNextBox. - End of Entry: As shown in the
txtSecondexample, you can move the focus to a “Submit” button or trigger another action once the final field is filled.
Summary
The small trick of “moving between input fields without pressing Tab” greatly improves the user experience. This method is easy to introduce, highly readable, and easy to maintain.
I highly recommend trying this in your business forms or personal projects to make data entry smoother.
