运行时错误 91 对象变量或未设置块变量

不正确的代码

Sub DoSomething()
    Dim foo As Collection
    With foo
        .Add "ABC"
        .Add "XYZ"
    End With
End Sub

为什么这不起作用?

对象变量包含引用,并且需要使用 Set 关键字设置引用。只要对引用为 Nothing 的对象进行成员调用,就会发生此错误。在这种情况下,fooCollection 引用,但它没有被初始化,所以引用包含 Nothing - 我们不能在 Nothing 上调用 .Add

正确的代码

Sub DoSomething()
    Dim foo As Collection
    Set foo = New Collection
    With foo
        .Add "ABC"
        .Add "XYZ"
    End With
End Sub

为什么这样做?

通过使用 Set 关键字为对象变量分配有效引用,.Add 调用成功。

其他说明

通常,函数或属性可以返回对象引用 - 常见的例子是 Excel 的 Range.Find 方法,它返回 Range 对象:

Dim resultRow As Long
resultRow = SomeSheet.Cells.Find("Something").Row

但是该函数可以很好地返回 Nothing(如果找不到搜索项),因此链接的 .Row 成员调用很可能失败。

在调用对象成员之前,请验证是否使用 If Not xxxx Is Nothing 条件设置了引用:

Dim result As Range
Set result = SomeSheet.Cells.Find("Something")

Dim resultRow As Long
If Not result Is Nothing Then resultRow = result.Row