VBA-如何在文本框中的特定位置设置光标?

问题描述:

标题主要说明了我的需求。我有一个文本框,使用 _keypress 过程不断检查数据的有效性。如果用户输入,那么我会通过键入右括号为他们自动填充。结果为(),并且光标位于文本框的末尾。
我的问题是,如何将光标后退一步以将其置于两个括号之间?谢谢,

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,

编辑:测试场景:

Private Sub txtInput_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)

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

End Sub

希望这使它更加清晰,

使用 SelStart 属性> TextBox 对象:

Use the SelStart property of the TextBox object:

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

注意: SelStart = 1 表示光标将位于第一个元素之后,即 。因此,您应该使用字符串来了解 SelStart 属性应为

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.