Link to home
Start Free TrialLog in
Avatar of FaheemAhmadGul
FaheemAhmadGulFlag for United Kingdom of Great Britain and Northern Ireland

asked on

VBA code to move the cursor to the start of a TextBox

This question is in a way related to a previous question I asked on this forum which is here.
https://www.experts-exchange.com/questions/29148228/VBA-code-to-detect-which-key-the-user-has-pressed-in-a-text-box.html?anchorAnswerId=42878897#a42878897

What I would like to be able to do is run some code, such as deleting all the Text in TextBox1 one when I press space key after typing some text in the TextBox1 and then displaying a message box saying "Hello" when the user presses the space key. The following does achieve this but after code has run it leaves the cursor in the TextBox1 some spaces
further away from the start point (depending on how many characters I had typed before pressing the space key). So if I press space key after typing abc in the TextBox and then press space key all text from TextBox1 gets cleared but the cursor is left four space away from the start point of the TextBox1. I would
like the cursor to be at the start of the TextBox1 when I press space key. So basically I am looking for a way of
moving the cursor to the starting point in the TextBox1 after my code has run.
Thank you for your help.

Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)

Select Case KeyAscii
 Case 32 'space
 TextBox1.Text = ""
MsgBox "Hello"
 ' the above line does clear the TextBox1 of all its text but it leaves the cursor in the TextBox1 some spaces
' further away from the start point. So if I press space key after typing abc in TextBox1 and then press space all text
' from TextBox1 gets cleared but the cursor is left four space away from the start point of the TextBox1. I would
 ' the cursor to be at the start of the TextBox1 when I press space key. So basically I am looking for a way of 
 ' moving the cursor to the starting point in the TextBox1 after the above code has run .
 
        'do something when the space is typed
 Case 48 To 57 'numeric value 0 to 9
        'do something when a numeric key value is typed (between 0 to 9)
 End Select


'
End Sub

Open in new window

Avatar of Martin Liss
Martin Liss
Flag of United States of America image

TextBox1.SelStart = 1 should do the trick.
ASKER CERTIFIED SOLUTION
Avatar of irudyk
irudyk
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I changed the code above. I had kept KeyAscii which should have been changed to KeyCode
TextBox1.SelStart = 1 will still keep the space that is entered. So, if that is what you want then you should use that.

If you don't want the space to remain then change the routine to a KeyUp event as noted above.
Avatar of FaheemAhmadGul

ASKER

Many thanks.
Greatly appreciated!