【问题标题】:Type Mismatch on VBA if StatementVBA if 语句类型不匹配
【发布时间】:2020-11-28 21:28:32
【问题描述】:

我有一个 if 语句检查变量转换为双精度的相等性。它检查变量是否包含任何内容,如果数字更大,则为 0。

但是,当我检查变量 (num1) = 0 还是 num1 = "" 时,我收到了类型不匹配错误。

num1 是从工作表中取出的数字作为双精度数:

num1 = loc.Cells(6, 5).Value 

这当前将 7800 的值分配给 num1:num1 = 7800

但是 ElseIf 语句中的代码错误表明存在类型不匹配:

ElseIf num1 = 0 Or num1 = "" Then
    GoTo nocurrentnumber
        If Not makenumber Then
            makenumber = NumberMaker(startdate, enddate)
            Set numbersheet = ThisWorkbook.Worksheets("Current Number")
        Else
        If PnL_Sheet.Cells(Startrow, i).Value > StartDate And PnL_Sheet.Cells(Startrow, i).Value <= EndDate Then
            PnL_Sheet.Cells(Startrow, numberLine).Value = number
        Else
        End If
        End If
nocurrentnumber:
    Else
        PnL_Sheet.Cells(Startrow, numberLine).Value = 0

设置为 double 的变量不应该能够检查这些类型的相等吗? 还是我错过了什么?

我已阅读以下帖子,每个帖子都提供了我认为我无法使用的答案:

Excel VBA Run-time error '13': Type mismatch

Excel VBA Run-time error '13' Type mismatch

Excel VBA: Type Mismatch

【问题讨论】:

  • 如果是双精度的话就不能是""?只有在我没记错的情况下,Double 才是数字
  • 是的,但是 num1 可能为空,所以我还需要检查是否为空。生病编辑我的帖子。您看到的是平等检查,而不是分配。
  • 但字符串不是空的。这就是区别。你的所作所为相当于我手里拿着一个球,问这车是什么颜色的。这个问题对口译员没有意义
  • 不是一个很好的解释,但现在我知道我需要检查 len 是否 > 0。
  • 长度将始终>0,因为变量可以容纳的最小值为0,因此长度为1。

标签: excel vba


【解决方案1】:

double 数据类型不能保存字符串,因此= "" 不正确。

VBA 中为空的数值数据类型(int、double、long 等)将保存值0

ElseIf num1 = 0 then

删除字符串比较。

参考:

https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/data-types/double-data-type
Double 的默认值为 0。

【讨论】:

    【解决方案2】:

    答案不是检查 num1 是否为空,而是检查 num1 的 len 是否大于 0。

    【讨论】:

    • 但根据定义,这不是一个空变量,因为它可以是负数和 0 并且仍然可以设置
    猜你喜欢
    • 2021-01-19
    • 1970-01-01
    • 2021-01-19
    • 1970-01-01
    • 2016-12-16
    • 1970-01-01
    • 2021-09-29
    • 2013-07-29
    • 1970-01-01
    相关资源
    最近更新 更多