VBA检查变量是否为空

问题描述 投票:42回答:4

我有一个对象,在其中我想检查一些属性是否设置为false,如:

If (not objresult.EOF) Then
  'Some code 
End if

但不知何故,有时objresult.EOFEmpty,我怎么检查它?

  • IsEmpty功能仅适用于excel细胞
  • objresult.EOF Is Nothing - 返回Empty
  • objresult.EOF <> null - 返回Empty
vba object variables is-empty
4个回答
81
投票

您如何测试取决于Property的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    |

您可以通过按F2启动对象浏览器并查找对象来告诉DataType。另一种方法是使用TypeName函数:MsgBox TypeName(obj.Property)


18
投票

要检查Variant是否为空,您需要这样做:

Isnull(myvar) = True

要么

Not Isnull(myvar)

11
投票

对于一个数字,它很棘手,因为如果数字单元格是empty,VBA将为其分配默认值0,因此您的VBA代码很难区分输入的零和空白数字单元格之间的区别。

以下检查对我有用,看看是否有一个实际的0进入单元格:

If CStr(rng.value) = "0" then
    'your code here'
End If

0
投票

我有一个类似的问题,一个整数可以在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
© www.soinside.com 2019 - 2024. All rights reserved.