執行時錯誤 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