Private Sub Text1_LostFocus()
'比如:在文本框失去焦点时检查输入的合法性,如果不合法,输入焦点停留在文本框。
If CheckValue(Text1.Text) <> True Then
Text1.SetFocus
End If
End Sub
'------------------------------------------
Function CheckValue(str As String) As Variant
'函数判断字符串是否合法,返回1 :不是数字 ;返回2 :数值范围不对;返回True:准确
'如果不要弹出提示框,把msgbox 句去掉
If Not str Like String(Len(str), "#") Then
checkValue = 1
MsgBox "非数字"
ElseIf Int(str) > 1000 Then
checkValue = 2
MsgBox "数值范围不对"
Else
checkValue = True
MsgBox "准确"
End If
End Function
Private Sub CommandButton1_Click()
Dim X As String
X = text1.text
Dim arr() As String
arr = Split(X)
Dim i As Integer
For i = 0 To UBound(arr)
if asc(arr(i)) > 48 and asc(arr(i)) < 57 then exit for
Next
If i = UBound(arr) + 1 then
if val(text1.text) < 0 or val(text1.text) > 1000 Then
text2.text= "错误2"
else
text2.text= "正确"
msgbox "并进行下一步程序。"
end if
Else
text2.text= "错误1"
End If
End Sub
Private Sub CommandButton1_Click()
Dim X As String
X = InputBox("请输入单个字符", "字符串")
Dim arr() As String
arr = Split(X)
Dim i As Integer
Dim strCnt, numCnt, otCnt As Integer
For i = 0 To UBound(arr)
Select Case arr(i)
Case "A" To "Z", "a" To "z"
strCnt = strCnt + 1
Case "0" To "9"
numCnt = numCnt + 1
Case Else
Print X + "是其他字符"
End Select
Next
If strCnt = UBound(arr) + 1 Then
MsgBox "是字符串"
ElseIf numCnt = UBound(arr) + 1 Then
MsgBox "是数字"
Else
MsgBox "其他字符"
End If
End Sub
你可以改变下思路,将tesxbox的最大长度限制为3,然后限制只能输入数字就可以实现只能输入0-999,输入其他字符是无效的,不会显示。如果你一定要实现能输入1000的话,就只有把长度设为4,那就在change事件中判断下是否大于1000
下面是实现0-999:
‘将textbox的maxlength设置为3
'-------------------
Private Sub Text1_KeyPress(KeyAscii As Integer)
If (KeyAscii < 48 Or KeyAscii > 57) And KeyAscii <> 8 Then
'屏蔽数字外的所有符号
KeyAscii = 0
End If
End Sub
根据acs判断就可以了
有问题请追问