假设我有我的EXCEL VBA用户窗体这下面的代码:
Private Sub TextBox_Change()
TextBox.Value = UCase(TextBox.Value)
OtherText.Value = "FOO " & TextBox.value & " BAR"
End Sub
它迫使文本框总是大写,并且效果很好当用户从端型。
不过说我得到了一个文本"HELLO WORLD"
,我想插入之间"CRUEL "
(由用户手动输入),只要我在C
输入,光标会D
后跳转到最终的结果将成为"HELLO CWORLDRUEL "
(如果我输入盲目)。
光标位置不会改变,如果我有大写锁定,但它违背了代码的目的......,用小写字符它总是踢光标到最后。
是否有维持这些类型的强制情况下改变光标所在位置的方法吗?
使用_Exit()
方法我曾经考虑过,但我确实想同时保留OtherText
并与每个更改大写TextBox
值。否则OtherText
将全部大写,而在执行TextBox
之前_Exit()
仍小写字母,看起来...不可取。
尝试使用不同的事件,如以下几点:
Private Sub TextBox_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
If KeyAscii >= 97 And KeyAscii <= 122 Then 'a-z
KeyAscii = Asc(UCase(Chr(KeyAscii)))
End If
End Sub
您可以使用SelStart
捕捉光标位置,然后重置光标当你做对文本进行处理。
Option Explicit
Private Sub TextBox1_Change()
Dim cursorPos As Long
cursorPos = Me.TextBox1.SelStart
Me.TextBox1.Text = UCase(Me.TextBox1.Text)
Me.TextBox1.SelStart = cursorPos
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
Cancel = True
Me.Hide
End Sub