Grendizer
Grendizer

Reputation: 292

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,

Upvotes: 9

Views: 29844

Answers (2)

MoSalah001
MoSalah001

Reputation: 11

Use the SelStart property with Len function

Me.txtInput.SelStart = Len(Me.txtInput.Value)-1

Using this method now you can be sure that it will always set the typing cursor between your parenthesis

Upvotes: 0

Matteo NNZ
Matteo NNZ

Reputation: 12655

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.

Upvotes: 9

Related Questions