如何在Excel VBA中返回变量的正确Integer数据类型?
解决Excel宏中自定义函数识别整数类型的问题
问题根源
Excel单元格中的数值默认以**Double(vbDouble,类型值5)**存储,哪怕输入的是整数(如2),直接通过VarType读取单元格.Value时,返回的依然是Double类型标识,而非Integer(vbInteger,类型值2)。这就是输入2或2.0000时,函数都返回5的原因。
修改后的自定义函数
我们需要在函数中增加逻辑:当检测到Double类型时,判断该数值是否为正整数且落在Integer的取值范围内(-32768到32767),如果符合条件则返回Integer的类型标识2,否则保持返回Double的标识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 ' 判断是否为正整数,且在Integer范围内 If FieldValue > 0 And Fix(FieldValue) = FieldValue And FieldValue <= 32767 Then InputCheck = 2 Else InputCheck = 5 End If End Select End Function
关键逻辑说明
Fix(FieldValue) = FieldValue:判断数值的整数部分是否等于自身,确认是整数(排除2.5这类带小数的情况)。FieldValue > 0:匹配研究ID为正整数的要求。FieldValue <= 32767:确保数值在VBA Integer类型的最大值范围内(Integer类型取值范围为-32768到32767)。
子过程调用验证
原有的子过程代码无需修改,调用修改后的InputCheck函数后,输入符合要求的正整数时,会正确弹出"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
内容的提问来源于stack exchange,提问作者Thomas Labelle
相关产品推荐
相关产品推荐

