Excel VBA里限制文本框里的输入的数据为正整数,如果不是正整数提示错误。

2025-02-25 12:34:43
推荐回答(2个)
回答1:

假设有文本框TextBox1
Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
If KeyAscii < 48 Or KeyAscii > 57 Then KeyAscii = 0
End Sub

加上这个代码,文本框里就只能输入正整数了,不用判断。

非要判断的话用这个代码,错误提示在A1里面表示
Private Sub TextBox1_Change()
If Val(TextBox1.Text) > 0 And InStr(TextBox1.Text, ".") = 0 Then
Range("A1").Value = "整数"
Else
Range("A1").Value = "非正整数"
End If
End Sub

回答2:

假设以A1为例,
Sub test()
With Range("A1")
If IsNumeric(.Value) Then
If Int(.Value) <> .Value Then MsgBox "不是整数"
If .Value < 0 Then MsgBox "不是正整数"
Else
MsgBox "不是数字"
End If
End With
End Sub