VBA 检查变量是否为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3329110/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VBA Check if variable is empty
提问by fessguid
I have an object and within it I wanna check if some properties is set to false, like:
我有一个对象,在其中我想检查某些属性是否设置为 false,例如:
If (not objresult.EOF) Then
'Some code
End if
But somehow, sometimes objresult.EOFis Empty, and how can I check it?
但不知何故,有时objresult.EOF是Empty,我该如何检查呢?
IsEmptyfunction is for excel cells onlyobjresult.EOF Is Nothing- returnEmptyobjresult.EOF <> null- returnEmptyas well!
IsEmpty功能仅适用于excel单元格objresult.EOF Is Nothing- 返回Emptyobjresult.EOF <> null——也回来Empty!
回答by Oorang
How you test depends on the Property's DataType:
您如何测试取决于属性的数据类型:
| Type | Test | Test2 | Numeric (Long, Integer, Double etc.) | If obj.Property = 0 Then | | Boolen (True/False) | If Not obj.Property Then | If obj.Property = False Then | Object | If obj.Property Is Nothing Then | | String | If obj.Property = "" Then | If LenB(obj.Property) = 0 Then | Variant | If obj.Property = Empty Then |
You can tell the DataType by pressing F2 to launch the Object Browser and looking up the Object. Another way would be to just use the TypeName function:MsgBox TypeName(obj.Property)
您可以通过按 F2 启动对象浏览器并查找对象来告诉数据类型。另一种方法是只使用 TypeName 函数:MsgBox TypeName(obj.Property)
回答by Valentin Despa
To check if a Variantis Null, you need to do it like:
要检查 aVariant是否为空,您需要这样做:
Isnull(myvar) = True
or
或者
Not Isnull(myvar)
回答by deasa
For a number, it is tricky because if a numeric cell is emptyVBA will assign a default value of 0 to it, so it is hard for your VBA code to tell the difference between an entered zero and a blank numeric cell.
对于数字,这很棘手,因为如果数字单元格是emptyVBA,则会为其分配默认值 0,因此您的 VBA 代码很难区分输入的零和空白数字单元格之间的区别。
The following check worked for me to see if there was an actual 0 entered into the cell:
以下检查对我有用,可以查看单元格中是否输入了实际的 0:
If CStr(rng.value) = "0" then
'your code here'
End If
回答by Galanor
I had a similar issue with an integer that could be legitimately assigned 0 in Access VBA. None of the above solutions worked for me.
我有一个类似的问题,一个整数可以在 Access VBA 中合法地分配为 0。以上解决方案都不适合我。
At first I just used a boolean var and IF statement:
起初我只是使用了一个布尔变量和 IF 语句:
Dim i as integer, bol as boolean
If bol = false then
i = ValueIWantToAssign
bol = True
End If
In my case, my integer variable assignment was within a for loop and another IF statement, so I ended up using "Exit For" instead as it was more concise.
在我的例子中,我的整数变量赋值是在一个 for 循环和另一个 IF 语句中,所以我最终使用了“Exit For”,因为它更简洁。
Like so:
像这样:
Dim i as integer
ForLoopStart
If ConditionIsMet Then
i = ValueIWantToAssign
Exit For
End If
ForLoopEnd

