Search code examples
excelvbatextboxuserform

Highlight Text in Userform TextBox


I want to select/highlight all text in a TextBox on my Userform. I already found >20 forums with the .SelStart and .SelLength solution but it is not working for me...

Are there settings or properties that I need to change to be able to use this?

This is my code:

Private Sub MaterialDescriptionTextBox_Exit(ByVal Cancel As MSForms.ReturnBoolean)
If Len(MaterialDescriptionTextBox.Value) > 40 Then
    MsgBox "The material description can not exceed 40 characters", vbInformation, "Too many characters"
    With Me.MaterialDescriptionTextBox
        .SetFocus
        .SelStart = 0
        .SelLength = Len(.Text)
    End With
End If

Sadly it does not do anything asside from displaying the MsgBox.

Thanks


Solution

  • You are missing a Cancel = True. The Cancel cancels the Exit event itself but any other code after that will still run.

    Private Sub MaterialDescriptionTextBox_Exit(ByVal Cancel As MSForms.ReturnBoolean)
        If Len(MaterialDescriptionTextBox.Value) > 40 Then
            MsgBox "The material description can not exceed 40 characters", vbInformation, "Too many characters"
            Cancel = True
            With MaterialDescriptionTextBox
                .SetFocus
                .SelStart = 0
                .SelLength = Len(.Text)
            End With
    
        End If
    End Sub