![](/img/trans.png)
[英]How to check if Variant is empty and assign other variable to it in Excel VBA
[英]VBA Check if variable is empty
我有一个对象,并且在其中要检查是否将某些属性设置为false,例如:
If (not objresult.EOF) Then
'Some code
End if
但是不知何故,有时objresult.EOF
为Empty
,如何检查它?
IsEmpty
函数仅适用于Excel单元格 objresult.EOF Is Nothing
-返回Empty
objresult.EOF <> null
返回Empty
! 测试方式取决于属性的数据类型:
| 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 |
您可以通过按F2启动对象浏览器并查找对象来告诉DataType。 另一种方法是只使用TypeName函数: MsgBox TypeName(obj.Property)
要检查Variant
是否为Null,您需要执行以下操作:
Isnull(myvar) = True
要么
Not Isnull(myvar)
对于数字,这很棘手,因为如果数字单元格为empty
VBA会为其分配默认值0,因此VBA代码很难分辨输入的零和空白数字单元格之间的差异。
以下检查对我有用,以查看是否在单元格中输入了实际的0:
If CStr(rng.value) = "0" then
'your code here'
End If
我也遇到了一个类似的问题,该整数可以在Access VBA中合法分配为0。 以上解决方案均不适合我。
首先,我只是使用了布尔var和IF语句:
Dim i as integer, bol as boolean
If bol = false then
i = ValueIWantToAssign
bol = True
End If
就我而言,我的整数变量赋值位于一个for循环和另一个IF语句中,因此我最终使用了“ Exit For”,因为它更加简洁。
像这样:
Dim i as integer
ForLoopStart
If ConditionIsMet Then
i = ValueIWantToAssign
Exit For
End If
ForLoopEnd
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.