I want to check if some cells in excel are empty. So I do a comparison with vbNullString, which worked fine. But now, it seems as if the comparison is true when the cells contain the number zero? How can this be?
Thanks for advices, Florian
答案 0 :(得分:0)
This happens because if the cell contains the number zero, then it's not empty.
The .Value
property of a Range
object in Excel is not typed if nothing is written yet. In other words, when the cell contains nothing, it's comparable with both string and numeric "empty" values:
Empty cell value = vbNullString --> True
because literally talking its value is ""
Empty cell value = 0 --> True
because numerically talking its value is 0
...and this happen because you still didn't type the value of that range object, so at run time the cell is still considered as containing a Variant
type (which means that the type is not defined, so it's like a zero if that was numerical and like an empty string if that was a string).
However, when you type 0
(or this is the output of a formula, such as =2-2
), you're assigning the type "Numeric" to that range. The cell becomes Numeric Which means:
Is the numerical null type (0
) equal to a null string? False
Is the numerical null type (0
) equal to zero? True
If you want zero to be considered as the Null
alternative to the string ""
(i.e. the constant vbNullString
), then you should enrich your condition with the numerical check .Value = 0
.