测试值是 Long 还是 Integer(无小数位)

Test if value is Long or Integer (no decimal places)

我需要测试 textbox1 和 textbox2 中的值是整数还是长整数(没有小数位)。

我试过这样的事情:

    Dim x As Integer
    Dim y As Integer

    x = TextBox1.Value
    y = TextBox2.Value

    If x = Int(x) Then
        'my code
    Else
        MsgBox("value is not an integer")

如果我输入 x=2.3,它不会显示 MsgBox,但会将值四舍五入为 2。

由于您已将 xtype 指定为 Integer,因此从文本框字符串到 Integer 已经发生了。因此 Int(x) 是一个空操作。

一个解决方法是使用类似

的东西
If IsNumber(TextBox1.Value) Then
    If Fix(TextBox1.Value) = TextBox1.Value Then
        'I am an integeral type.
    End If
End If

在这里,Fix 截断了数字类型,我依靠 VBA 来进行正确的比较。请注意 VBA 没有实现 short-circutted And 所以你需要使用嵌套的 If 或类似的。

这是另一种方法(伪代码,所以请检查语法!)

Dim l_Temp_D1 as Decimal
Dim l_Temp_D2 as Decimal
Dim l_Temp_I  as Integer

l_Temp_I  = TextBox1.Value
l_Temp_D1 = TextBox1.Value
l_Temp_D2 = l_Temp_I

if (not IsNumber(TextBox1.Value)) then
    ' Error!!!
End If

if (l_Temp_D1 = l_Temp_D2) then
  ' Integer
  ...
else
  ' Float
  ...
End If

您不能在 VBA 中 Dim var as Decimal,但可以 Dim var as Variant 并使用 var = CDec(...) 在变体中存储十进制数据类型。即便如此,我发现小数点后有 14 或 15 个零后跟数字(或从整数中减去的等效小数点)四舍五入为整数。我还没有找到区分小数和整数的解决方案。