SetFocus for textbox on userform

YasserKhalil
PlatinumLounger
Posts: 4913
Joined: 31 Aug 2016, 09:02

SetFocus for textbox on userform

Post by YasserKhalil »

Hello everyone
I am trying to move the cursor inside a textbox on userform and I used SetFocus method but doesn't seem to work for me. The code is AfterUpdate event for the textbox. I even tried to use SelStart = 1

User avatar
HansV
Administrator
Posts: 78457
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: SetFocus for textbox on userform

Post by HansV »

Can you explain what you are trying to do and why?
Best wishes,
Hans

YasserKhalil
PlatinumLounger
Posts: 4913
Joined: 31 Aug 2016, 09:02

Re: SetFocus for textbox on userform

Post by YasserKhalil »

I have a textbox and I am using theis textbox to enter several entries, so I need to enter an entery then press Enter key and so on without the need to set the cursor inside the textbox every time.

User avatar
HansV
Administrator
Posts: 78457
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: SetFocus for textbox on userform

Post by HansV »

I'd use the KeyDown event:

Code: Select all

Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
    Select Case KeyCode
        Case vbKeyReturn, vbKeyTab
            ' Don't leave the text box when the user presses Enter or Tab
            KeyCode = 0
            ' Optional: select the entire text
            With Me.TextBox1
                .SelStart = 0
                .SelLength = Len(.Text)
            End With
    End Select
End Sub
Best wishes,
Hans

YasserKhalil
PlatinumLounger
Posts: 4913
Joined: 31 Aug 2016, 09:02

Re: SetFocus for textbox on userform

Post by YasserKhalil »

Amazing. That works well for me. Thank you very much.