How to move the cursor to the end of a text box in a Keydown event

randika100100

Registered User.
Local time
Tomorrow, 03:40
Joined
Aug 31, 2011
Messages
11
Hi All!
I have a live search in my form and searchtxt is the text box that users insert values to search.But in the process textbox looses focus and to get the focus and to set the cursor to the end of the already entered text I put

Me.searchtxt.SetFocus
Me.searchtxt.SelStart = Me.searchtxt.SelLength

It worked properly. But now I want to be able to identify if user has pressed space then add a space to the end of the text box so I put the following code in the KeyDown event

If keycode = 32 Then
Me.searchtxt.SetFocus
Me.searchtxt.Text = searchtxt.Text & " "
Me.searchtxt.SelStart = Me.searchtxt.SelLength

Else

Me.searchtxt.SetFocus
Me.searchtxt.SelStart = Me.searchtxt.SelLength

End If

But it doesn't work the way I want. Instead of adding a space to the end of the text, it adds a space to the beginning of the text . I tried few different things and non of them worked.:confused:
Can someone help me? Thanks in advance.
 
Shouldn't these lines be the other way around?

Me.searchtxt.Text = searchtxt.Text & " "
Me.searchtxt.SelStart = Me.searchtxt.SelLength


BTW. Your code would be better using With Blocks
Code:
With Me.searchtxt
   If keycode = 32 Then
      .SetFocus
      .SelStart = .SelLength 
      .Text = .Text & " "
   Else
      .SetFocus
      .SelStart = .SelLength
   End If
End With
 
Shouldn't these lines be the other way around?

Me.searchtxt.Text = searchtxt.Text & " "
Me.searchtxt.SelStart = Me.searchtxt.SelLength


BTW. Your code would be better using With Blocks
Code:
With Me.searchtxt
   If keycode = 32 Then
      .SetFocus
      .SelStart = .SelLength 
      .Text = .Text & " "
   Else
      .SetFocus
      .SelStart = .SelLength
   End If
End With

Thanks for the reply. I have tried this way before and it didn't work either :(
 
Code:
With Me.SearchText

   If KeyCode = 32 Then
       .SetFocus            
       .SelStart = Len(.Text)
   End If
        
End With
 
¿Puede alguien por favor ayudarme con esto? Estoy totalmente atrapado aquí:(
Buenos dias amigos del foro, lo solucione agregando un KeyDown:
Private Sub txtSearch_KeyDown (KeyCode como entero, Shift como entero)
Seleccionar código clave de caso
Caso vbKeySpace
txtBuscar = txtBuscar + " "
Código clave = 0
Finalizar Seleccionar
txtSearch.SetFocus
Me.txtSearch.SelStart = Len(txtSearch.Text)
Finalizar sub
 
Good morning, friends of the forum, I solved it by adding a KeyDown:
Private Sub txtSearch_KeyDown(KeyCode As Integer, Shift As Integer)
Select Case KeyCode
Case vbKeySpace
txtSearch = txtSearch + " "
KeyCode = 0
End Select
txtSearch.SetFocus
Me.txtSearch.SelStart = Len(txtSearch.Text)
End Sub
 

Users who are viewing this thread

Back
Top Bottom