Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading