限制文本框的输入 如果你运用过VBA用户窗体,那么你肯定使用过文本框控件。在某些情况下,你可能想限制用户在文本框中输入某类型的数据,比如在文本框中仅能输入数字。不巧的是,没有内置的属性能限制在文本框中只能输入数字。但你能在文本框对象的KeyPress事件过程中使用一些简单的代码来测试能输入哪类字符,然后(作修改后)仅允许数字字符输入。 例如,假设将用户窗体中的文本框命名为TextBox1,下面的代码将允许在文本框中输入数字0-9、一个句点和负号。代码限制用户输入的数据中包含小数点,并且只局限于将负号作为第一个字符输入。 Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger) Select Case KeyAscii Case Asc("0") To Asc("9") Case Asc("-") If Instr(1,Me.TextBox1.Text,"-") > 0 Or Me.TextBox1.SelStart > 0 Then KeyAscii = 0 End If Case Asc(".") If InStr(1, Me.TextBox1.Text, ".") > 0 Then KeyAscii = 0 End If Case Else KeyAscii = 0 End Select End Sub 如果想在文本框中允许其它类型的字符输入,在代码的第一个Case语句中列出(允许输入的字符)即可。 (译者注:该代码能允许中文字符的输入,但不能输入句点。By fanjy in 2006-6-22) 附:原文 Restricting Entry In Text Box If you are using a VBA Userform, you are almost surely using the TextBox control, and in many of these circumstances you may wish to restrict what sort of data the user is allowed to enter, such as numeric only. Unfortunately, there is no built-in property to restrict a text box to numeric only. However, you can use some simple code in the KeyPress event procedure of the TextBox object to test which character was entered, and allow only numeric (and supporting) characters. For example, suppose your textbox is named TextBox1. The following code will allow the digits 0-9, a period (.) and a negative sign. The code also limits the user to including a single decimal point, and restricts the minus sign to the first character. Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger) Select Case KeyAscii Case Asc("0") To Asc("9") Case Asc("-") If Instr(1,Me.TextBox1.Text,"-") > 0 Or Me.TextBox1.SelStart > 0 Then KeyAscii = 0 End If Case Asc(".") If InStr(1, Me.TextBox1.Text, ".") > 0 Then KeyAscii = 0 End If Case Else KeyAscii = 0 End Select End Sub To allow other characters, list them in the first Case statement. (By Chip Pearson) |