vba - 在 Excel VBA 中设置默认 TextBox.Value TypeName
问题描述
我有一个 vba 函数,用于检查来自文本框的用户输入是否为正整数。下面的代码:
Public Function IsPosInteger(n As Variant) As Boolean
If IsNumeric(n) = True Then
If (n = Int(n)) And n > 0 Then
IsPosInteger = True
Else
IsPosInteger = False
End If
Else
IsPosInteger = False
End If
End Function
问题是,在测试该函数时,对于有效的正整数仍然返回 false。经过进一步调查,我注意到 texbox 值的默认变量类型是字符串。可能是 IsNumeric 返回 false 的主要原因。
下面的函数是我用来确定变量类型的。
TypeName(n)
解决方案
Public Function IsPosInteger(s As String) As Boolean 'boolean data type is false by default.
If (IsNumeric(s) = False) Then Exit Function
If (s < 1) Then Exit Function
If (InStr(s, ".") = False) Then IsPosInteger = True
End Function
函数测试输入是否为数字,不小于 1,并且不包含小数。这是一个如何在调用子中使用它的示例:
Sub TestInput()
Dim sUserInput As String
Dim boolPositiveInt As Boolean
Dim i As Integer
sUserInput = Range("A1").Value2
boolPositiveInt = IsPosInteger(sUserInput)
If (boolPositiveInt = False) Then
MsgBox "Invalid input. Please enter a positive integer"
Exit Sub
End If
i = CInt(sUserInput)
'continue working with integer variable here
End Sub
推荐阅读
- python - Dask调度程序为空/图表未显示
- c# - 调用 SendEmailAsync 时 Stream 不支持阅读
- html - 在全屏桌面上隐藏字体可怕的图标
- powershell - Powershell REST API 调用返回 HTML 而不是 JSON
- php - Capture Screenshot API PageSpeed Insight 的问题
- c++ - 如何打印 .txt 单词列表中的单词?
- java - 返回响应之前调用的类方法
- java - Mesibo 消息列表标题显示数字但我想要用户名
- google-chrome-extension - Chrome 扩展程序:无法解压缩扩展程序
- json - 在PowerShell中解析json的麻烦