首页 > 解决方案 > 在 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)

标签: vbaexcel

解决方案


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

推荐阅读