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

2

9

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,

Heffernan answered 8/2, 2015 at 21:19 Comment(0)
C
9

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.

Chantellechanter answered 8/2, 2015 at 22:1 Comment(4)
One more question, is there a way to return the position number where the cursor is?Heffernan
You will need to make a call to Windows API check support.microsoft.com/kb/152969/en-us?wa=wsignin1.0Chop
Do I need that to return the position of the cursor in a textbox?Heffernan
@Heffernan I guess it's the same property, SelStart. If you write "SelStart = 2" you're setting its value, but if you write pos = SelStart you should be getting its value.Chantellechanter
K
0

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

Kevenkeverian answered 4/9, 2022 at 12:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.