【问题标题】:Wrong variable data type returned with VarType Excel VBA functionVarType Excel VBA 函数返回了错误的变量数据类型
【发布时间】:2022-07-23 02:50:32
【问题描述】:

我有一个关于 Excel 中的 VarType 函数的简单问题。

我正在 Excel 中编写一个宏,它使用自定义函数来验证表单中字段的数据类型,以便稍后验证用户输入。有问题的字段由研究 ID 组成,是一个 正整数,从 1 到 n

我的函数的问题是它似乎没有返回预期的整数数据类型。

当我在字段中以整数形式输入数字(例如,2)时,我的函数返回 5 (VbDouble),根据this link 是双精度浮点数。请注意,我已经使用 2.0000 和 2 测试了字段输入,并且都返回 5。

在字段中输入“2”时的预期结果应该是 2(整数)而不是 5。

请看下面我构建的自定义函数的代码:

Function InputCheck(FieldValue As Variant) As Integer
    Dim TypeCheck As Integer
    TypeCheck = VarType(FieldValue)
    Select Case TypeCheck
    Case 2 'Integer
        InputCheck = 2
    Case 3 'Long integer
        InputCheck = 3
    Case 4 'Single-precision floating-point number
        InputCheck = 4
    Case 5 'Double-precision floating-point number
        InputCheck = 5
    End Select
End Function

在我的 Sub 中,下面的代码应该显示正确的数据类型(整数)。

If InputCheck(.Cells(iRow, 2).Value) = 2 Then
   MsgBox "Integer"
ElseIf InputCheck(.Cells(iRow, 2).Value) = 3 Then
   MsgBox "Long integer"
ElseIf InputCheck(.Cells(iRow, 2).Value) = 4 Then
   MsgBox "Single-precision floating-point number"
ElseIf InputCheck(.Cells(iRow, 2).Value) = 5 Then
   MsgBox "Double-precision floating-point number"
End If

我的问题如下:如何为相关字段的用户定义函数返回相关字段的正确数据类型(2,整数),而不是当前数据类型目前返回 5 个?

任何帮助将不胜感激!

【问题讨论】:

标签: excel vba user-defined-functions


【解决方案1】:

您的VarType 只是要读取您定义变量的类型。 我将您的as integer 更改为 as string,因为我认为这会删除一个步骤,但您可以轻松地回到旧的方式。如果您需要更具体的答案,还可以添加更多条件。

Option Explicit

Sub Test()
    MsgBox InputCheck(InputBox("Enter Data to test", "DataTypeTest", "")), vbOKOnly, "DataTypeTest"
End Sub

Function InputCheck(FieldValue) As String
    If IsNumeric(FieldValue) Then
        If --FieldValue = Round(FieldValue, 0) Then
            InputCheck = "Integer" '(Or long or whatever...)
            Exit Function
        Else
            InputCheck = "Decimal" '(or double.. or whatever you want to call it)
            Exit Function
        End If
    Else
        If IsDate(FieldValue) Then
            InputCheck = "Date"
            Exit Function
        Else
            InputCheck = "String"
            Exit Function
        End If
    End If
End Function

使用 msgbox sub 进行测试。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多