excel - 如果 x <> Int(x) 始终为真,即使 x=Int(x)。找不到原因

标签 excel vba

我在编码方面非常业余,但我正在尝试在 excel 中开发一些自动化业务表,以使我老人的业务生活更轻松一些。 目的是根据用户表单中的数字创建具有范围的表。 代码如下所示:(textbox1 被重命名为 nParc)

Private Sub Cmb1_Click()

Dim nP As Variant

    nP = UserForm1.nParc.Value

If nP = "" Then
    MsgBox "Error 0"
ElseIf Not IsNumeric(nP) Then
    MsgBox "Error 1"
ElseIf Not nP > 0 Then
    MsgBox "Error 2"
ElseIf nP <> Int(nP) Then
    MsgBox "Error 3"
Else
ActiveSheet.ListObjects.Add(xlSrcRange, Range(Cells(1, 1).Address(), Cells(nP, 14).Address()), xlYes).Name = "Business"
End If

End Sub

我总是得到

Error 3

当我点击“继续”按钮时,无论如何。如果我删除 msgbox "error 3"和 else 之后,它的工作原理。

我已经尝试使用 ElseIf Not nP = Int(nP),但问题仍然存在。

任何帮助将不胜感激。

最佳答案

让我详细说明@bigben 提供的答案并解释到底发生了什么。

比较

如果您使用 VarType 函数查看 npInt(np) 的值类型,您会看到 VarType(np) = 8,即np是一个String,VarType(Int(np)) = 5,即Int(np) 是一个 Double。由于两者都被声明为 Variant---Int 根据 paragraph 6.1.2.3.1.18 of the language specs 返回 Variant ---,paragraph 5.6.9.5 of the language specs结尾的特例被触发。

There is an exception to the rules in the preceding table when both operands have a declared type of Variant, with one operand originally having a value type of String, and the other operand originally having a numeric value type. In this case, the numeric operand is considered to be less than (and not equal to) the String operand, regardless of their values.

这就是比较返回 False

的原因

数字检查

您可能想知道为什么 IsNumeric(np) = True 尽管 np 是一个字符串。这实际上是 VBA 标准库中的一个错误。根据paragraph 6.1.2.7.1.8 of the language specs , IsNumeric 应在变量的值类型为 String 时返回 False。然而,实际上它似乎试图转换为 Double 并返回是否成功。

补救措施

正如@bigben 已经提到的,您应该将输入从 TextBox 转换为另一种类型。如果您只是将 np 声明为 String,它就可以工作,尽管在 IsNumeric 检查之后分配给 Double 类型的变量会更合适。

关于excel - 如果 x <> Int(x) 始终为真,即使 x=Int(x)。找不到原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63515440/

相关文章:

vba - 如何使用excel VBA删除第一列中包含特定代码的行?

vba - 检查工作表名称以避免重复

vba - Excel VBA 中的 "Object Library invalid or contains references..."和 DatePicker

arrays - 带有动态数组的 VBA 字典

excel - 根据 sheet1(table1) 中同一行中的值复制特定单元格并粘贴到 sheet2(table2) 下一个可用行

java - 如何打开从java arraylist导出的excel文件

vba - 我的 Sub 无法识别连接的字符串

vba - 识别公式中的当前单元格

excel - 如何在 Excel 2010 中使用 VBA 查询 UTF-8 编码的 CSV 文件?

vba - 除了自定义错误处理程序之外,如何在使用默认错误处理程序时避免级联