我正在Excel中编写一个宏,该宏使用自定义函数来验证表单中字段的数据类型,以便稍后验证用户输入。该字段由研究ID组成,是一个正整数,从1到n不等。
当我以整数的形式输入字段中的数字(例如,2)时,我的函数返回5 (VbDouble),根据此链接,这是一个双精度浮点数。
我用2.0000和2测试了字段输入,并且都返回了5。
将"2“输入字段时的预期结果是2(整数)。
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中,下面的代码应该显示数据类型(Integer)。
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,Integer)?
发布于 2022-07-22 18:50:32
您的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 CDbl(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潜艇进行测试。
https://stackoverflow.com/questions/73083926
复制相似问题