excelvbatextboxuserformsetfocus

SetFocus in Userform for Textbox


I have a userform with a textbox for a date. On exit I test if the entered value is a date and if not a MsgBox pops up, informing about the entry being invalid.

Private Sub tbRGDatum_Exit(ByVal Cancel As MSForms.ReturnBoolean)

With tbRGDatum
    If IsDate(.Value) Then
        .Text = Format(.Text, "dd.mm.yyyy")
    Else
        MsgBox "Bitte gültiges Datum im Format DD.MM.YYYY eingeben"
        .SetFocus
    End If
End With

End Sub

I want the cursor to be back in the textbox, so people are forced to make a correct entry.

I tried .SetFocus and .SelStart = 1. Both had no effect. After exiting, the MsgBox pops up but the cursor is not in the box. No error message.

I also tried tbRGDatum.SetFocus below End With instead of inside, to test it, nothing happened.

Suspecting the MsgBox to be the culprit, I tried the code without it.

I also tried _AfterUpdate as event handler with the same result.


Solution

  • Pls. try Cancel set to True in case false data entry. This cancel the Exit event.

    With tbRGDatum
        If IsDate(.Value) Then
            .Text = Format(.Text, "dd.mm.yyyy")
        Else
            MsgBox "Bitte gültiges Datum im Format DD.MM.YYYY eingeben"
            Cancel = True
        End If
    End With
    
    End Sub