'setting focus back to a textbox
I need to check if a text box is empty/null or blank before my user moves onto the next field on the user form. here is the code that checks if the textbox is empty/null/blank. My issue is that it does not return the focus to the textbox, but moves onto the next field in the user form.
Private Sub txtTDYLocation_lostfocus()
Dim Pcase As String
'converts text to proper case
If Trim(txtTDYLocation.Value & "") = "" Then
MsgBox "Please enter TDY location", vbOKOnly
txtTDYLocation.SetFocus
Else
Pcase = Me.txtTDYLocation
Pcase = StrConv(Pcase, vbProperCase)
Me.txtTDYLocation.Text = Pcase
Me.txtTDYLocation = StrConv(Me.txtTDYLocation, 3)
End If
End Sub
Solution 1:[1]
For this to work you should use the event txtTDYLocation_BeforeUpdate and cancel the change if value is Null in the textbox. Once Cancel is set to True the focus will not be able to leave the textbox.
Private Sub txtTDYLocation_BeforeUpdate(Cancel As Integer)
If Trim(txtTDYLocation & "") = "" Then
MsgBox "Please enter TDY location", vbOKOnly
Cancel = True
End If
End Sub
And in txtTDYLocation_AfterUpdate() you can change the value.
Private Sub txtTDYLocation_AfterUpdate()
Dim Pcase As String
'converts text to proper case
If Trim(txtTDYLocation.Value & "") <> "" Then
Pcase = Me.txtTDYLocation
Pcase = StrConv(Pcase, vbProperCase)
Me.txtTDYLocation.Value = Pcase
Me.txtTDYLocation = StrConv(Me.txtTDYLocation, 3)
End If
End Sub
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jeremy Caney |
