1输入框inputbox,要求只能输入几个数字
1.1代码1:可以运行
- 实现效果
- 必须输入 指定数字的数字
- 如果超过了指定的 字符数,会报错,且要求重新输入
- 如果输入的字符不是数字,或数字字符串 (input输入的一定是string),会报错,且要求重新输入
- 以后可以考虑加个多次错误,跳出,结束。
Sub ponyma_in1()
input101:
str1 = InputBox("请输入0~9之间的任一数字")
If Len(str1) >= 2 Then
MsgBox "您输入的字符超过了1个"
GoTo input101:
ElseIf Not IsNumeric(str1) Then '不用转?
MsgBox "您输入的不是数字"
GoTo input101:
Else
num1 = Int(str1)
End If
MsgBox "OK,get it," & num1 & ",thank you"
Debug.Print num1
End Sub
1.2 代码2: 注释里是曾经想做的代码
- On Error Resume Next
- On Error GoTo input101:
- ElseIf Application.IfError(Int(str1)) Then '想用报错不好使
- MsgBox "您输入的不是数字"
- GoTo input101:
Sub ponyma_in1()
'On Error Resume Next
'On Error GoTo input101:
input101:
str1 = InputBox("请输入0~9之间的任一数字")
If Len(str1) >= 2 Then
MsgBox "您输入的字符超过了1个"
GoTo input101:
'ElseIf Application.IfError(Int(str1)) Then '想用报错不好使
' MsgBox "您输入的不是数字"
' GoTo input101:
ElseIf Not IsNumeric(str1) Then '不用转?
MsgBox "您输入的不是数字"
GoTo input101:
Else
num1 = Int(str1)
End If
MsgBox "OK,get it," & num1 & ",thank you"
Debug.Print num1
End Sub
2 判断数字/数字字符串函数
2.1 isnumber() 和 isnumeric()
- 所属的库不同.在对象浏览器中可以查看到.,一个是工作表函数,一个是VBA函数
- 语法写法差别
- application.isnumber()
- worksheetfunction.isnumber()
- application.worksheetfunction.isnumber()
- isnumeric()
- isnumber(),可以在工作表使用,也可以VBA内使用
- 只能是数字才行
- isnumeric()只能在VBA使用
- 检测变量是否为数字或数字字符串,文本型数字也判断为True
- 如果 var 是数字和数字字符串则返回 TRUE,否则返回 FALSE。
- 在VBS中,IsNumeric()函数的实际作用是判断参数表达式是否是数值,而这个所谓的“数值”不仅仅包含普通的数字,还包括(但可能不限于)如下情况:
- 1、科学计数法表达式,如“2e7”和“2d7”;
- 2、十六进制数,如“&H0A”;
- 3、八进制数,如“&6”;
- 4、当前区域下设置的货币金额表达式,如“¥12.44”;
- 5、加圆括号的数字,如“(34)”;
- 6、显式指定正负的数字,如“+2.1”和“-2.1”;
- 7、含有逗号的数字字符串,如“12,25”。
2.2 代码3 测试isnumeric()
- 变量 a ,甚至 a=b1 VBA里都认为是变量
- 字符串"a",才是string
- isnumeric() 有时候判断 a1 这种为true ,是因为a1 这种变量为空(false,等价于0)
Sub cs1()
a1 = 3
b1 = "3"
c1 = a3
d1 = a
Debug.Print Application.IsNumber(a1)
Debug.Print Application.IsNumber(b1)
Debug.Print Application.IsNumber(c1)
Debug.Print Application.IsNumber(d1)
Debug.Print
Debug.Print "a1=" & a1
Debug.Print "b1=" & b1
Debug.Print "c1=" & c1
Debug.Print "d1=" & d1
Debug.Print
Debug.Print IsNumeric(a1)
Debug.Print IsNumeric(b1)
Debug.Print IsNumeric(c1)
Debug.Print IsNumeric(d1)
Debug.Print
'看起来字符串必须引号"" 引起来
'或者是有些函数返回的,指定是字符串型
j1 = 3
k1 = "3"
l1 = "a3"
m1 = "a"
Debug.Print IsNumeric(3)
Debug.Print IsNumeric("3")
Debug.Print IsNumeric("a3")
Debug.Print IsNumeric("a")
Debug.Print
Debug.Print IsNumeric(j1)
Debug.Print IsNumeric(k1)
Debug.Print IsNumeric(l1)
Debug.Print IsNumeric(m1)
Debug.Print
End Sub

本文介绍如何在VBA中使用输入框限制用户输入特定数量的数字,并探讨了isnumber()与isnumeric()函数的区别及应用。通过代码示例,展示了如何确保用户输入符合预期的数字格式。
1421

被折叠的 条评论
为什么被折叠?



