Search code examples
excelvbatextboxuserformsetfocus

SetFocus has no effect in Userform for Textbox


I have a UserForm with a textbox for a date. On Exit I want to test if the entered Value is a date and if not a MsgBox pops up, informing about the entry beeing invalid. This works all fine.

But I also want the cursor to be back in the textbox, so people are forced to make a correct entry. I Tried it with .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 either. What am I missing?

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

In desperation I also tried to put tbRGDatum.SetFocus below End With instead of inside, just to test it, but still, nothing happened.

Suspecting the MsgBox to be the culprit, I tried the code without it, to no avail. Also I tried using _AfterUpdate as event handler with the same result.

Looking forward to your suggestions!


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