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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28399480/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 06:09:10  来源:igfitidea点击:

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

vbatextboxcursor

提问by Grendizer

The title mostly explains what I need. I have a textbox that I continuously examine for data validity using the _keypressprocedure. 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,

标题主要解释了我需要什么。我有一个文本框,我使用该_keypress程序不断检查数据有效性。如果用户输入,(我会通过键入右括号为他们自动填充它)。结果是(),光标位于文本框的末尾。我的问题是,如何将光标向后推一步以将其放在两个括号之间?谢谢,

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,

希望这能让它更清楚,

采纳答案by Matteo NNZ

Use the SelStartproperty of the TextBoxobject:

使用对象的SelStart属性TextBox

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

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

注意:SelStart=1表示光标会在第一个元素之后,即“ (”。因此,您应该使用字符串来了解您想要的SelStart属性值应该是什么。