vba是在相等比较中被视为零的空值

时间:2022-03-04 22:59:08

I am trying to skip records which either have a zero as the value or is empty. As of now, i have the following code that checks for both explicitly, but I feel that the second check is redundant. But I want to confirm that I am right so that I can remove the second part of the IF

我试图跳过记录,其值为零或为空。截至目前,我有以下代码明确检查两者,但我觉得第二次检查是多余的。但我想确认我是对的,以便我可以删除IF的第二部分

IF (CellInValue(RowInCrnt, ColInCrnt) = 0 Or CellInValue(RowInCrnt, ColInCrnt) = "") Then

2 个解决方案

#1


5  

No, "" is not equal to 0 and will produce a type mismatch in a strongly typed scenario, or won't come out as equal if used as Variant.

不,“”不等于0并且会在强类型场景中产生类型不匹配,或者如果用作Variant则不会相等。

When the cell is empty, it's also not the same as zero, but it will come out as same, because in VB, Empty = 0 gives True because of implicit conversion happening in the background.
Same for Empty = "", will also give True for the same reason.

当单元格为空时,它也与零不同,但它会相同,因为在VB中,由于在后台发生隐式转换,因此Empty = 0给出True。对于Empty =“”也是如此,出于同样的原因也会给出True。

So you need both checks.

所以你需要两个检查。

#2


3  

GSerg is completely correct.

GSerg是完全正确的。

If you really wanted to avoid doing 2 different checks, you could change your If to something like this:

如果你真的想避免做两个不同的检查,你可以将你的If更改为:

If Clng(0 & CellInValue(RowInCrnt, ColInCrnt)) = 0 then

This returns true when CellInValue(RowInCrnt, ColInCrnt) is "", Empty, or 0.

当CellInValue(RowInCrnt,ColInCrnt)为“”,空或0时,返回true。

Though if your function could return letters instead of numbers, this will have a type mismatch error in that case.

虽然如果你的函数可以返回字母而不是数字,那么在这种情况下会出现类型不匹配错误。

#1


5  

No, "" is not equal to 0 and will produce a type mismatch in a strongly typed scenario, or won't come out as equal if used as Variant.

不,“”不等于0并且会在强类型场景中产生类型不匹配,或者如果用作Variant则不会相等。

When the cell is empty, it's also not the same as zero, but it will come out as same, because in VB, Empty = 0 gives True because of implicit conversion happening in the background.
Same for Empty = "", will also give True for the same reason.

当单元格为空时,它也与零不同,但它会相同,因为在VB中,由于在后台发生隐式转换,因此Empty = 0给出True。对于Empty =“”也是如此,出于同样的原因也会给出True。

So you need both checks.

所以你需要两个检查。

#2


3  

GSerg is completely correct.

GSerg是完全正确的。

If you really wanted to avoid doing 2 different checks, you could change your If to something like this:

如果你真的想避免做两个不同的检查,你可以将你的If更改为:

If Clng(0 & CellInValue(RowInCrnt, ColInCrnt)) = 0 then

This returns true when CellInValue(RowInCrnt, ColInCrnt) is "", Empty, or 0.

当CellInValue(RowInCrnt,ColInCrnt)为“”,空或0时,返回true。

Though if your function could return letters instead of numbers, this will have a type mismatch error in that case.

虽然如果你的函数可以返回字母而不是数字,那么在这种情况下会出现类型不匹配错误。