测试值是长整型还是整数(无小数位)

问题描述 投票:0回答:4

我需要测试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。

excel vba integer long-integer
4个回答
4
投票

由于您已将 x

type
指定为
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
或类似的。


1
投票

在 VBA 中不能

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


0
投票

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

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

0
投票

这是解决我的问题的一段代码

函数 isInteger(num As String) As Boolean Dim iNum 作为整数 出错时继续下一步

iNum = CInt(num)
If Err.Number = 0 Then isInteger = True
Err.clear

结束功能

子 test_isInteger() Dim bool 作为布尔值 将 str 调暗为字符串

str = "1234567890"
bool = isInteger(str)  ' --> FALSE

str = "12345"
bool = isInteger(str)  ' --> TRUE

结束子

© www.soinside.com 2019 - 2024. All rights reserved.