Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA - How to Set Cursor in a Specific Position in a Textbox?

The title mostly explains what I need. I have a textbox that I continuously examine for data validity using the _keypress procedure. If the user enters ( then I auto-fill it for them by typing the closing parenthesis ). The result is () and the cursor is at the end of the textbox. My question is, how can I push the cursor back one step to put it between the two parenthesis? Thanks,

Edit: Test scenario:

Private Sub txtInput_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)

    If KeyAscii = Asc("(") Then
        txtInput.value = txtInput.value & "()"
        KeyAscii = 0
    End If

End Sub

Hope this makes it more clear,

like image 987
Grendizer Avatar asked Feb 08 '15 21:02

Grendizer


1 Answers

Use the SelStart property of the TextBox object:

Me.TextBox1.Value = "()"
Me.TextBox1.SelStart = 1

Note: SelStart=1 means the cursor will be after the first element, i.e. "(". You should hence play with your string to understand what your desired value of SelStart property should be.

like image 143
Matteo NNZ Avatar answered Oct 12 '22 23:10

Matteo NNZ