2
好的,所以我正在嘗試在VBA for Excel中編寫一個簡單的腳本,該腳本根據用戶在電子表格中的單元格中選擇的某個值更改AutoFilter。到目前爲止,它一直工作得非常好,但現在我發現了以下錯誤,我想不出什麼原因引起的:什麼是運行時錯誤91,以及它爲什麼顯示在我的Excel VBA腳本中?
運行時錯誤「91」:對象變量或帶塊變量未設置
記住這是字面上的第一次我曾經嘗試過寫任何東西在VBA所以我不是很熟悉的語言。儘管我對Excel非常熟悉,但我也知道其他幾種編程語言(Java,JavaScript,Ruby,LUA)。
下面是我寫的代碼;錯誤發生在第9行。
Private Sub Worksheet_Change(ByVal Target As Range)
'' Review Level Changed ''
If Target.Address = Worksheets("Sheet1").Range("review_level").Address Then
' MsgBox "You just changed " & Target.Address & " to " & Target.Value ' Debug
Dim oldProtection As Protection
If Worksheets("Sheet1").ProtectContents = True Then
oldProtection = Worksheets("Sheet1").Protection ' It errors out here
Worksheets("Sheet1").Unprotect
End If
If Target = "B" Then
ActiveSheet.ListObjects("review_checklist").Range.AutoFilter Field:=2, _
Criteria1:=Array("B", "C", "D"), Operator:=xlFilterValues
ElseIf Target = "C" Then
ActiveSheet.ListObjects("review_checklist").Range.AutoFilter Field:=2, _
Criteria1:="=C", Operator:=xlOr, Criteria2:="=D"
ElseIf Target = "D" Then
ActiveSheet.ListObjects("review_checklist").Range.AutoFilter Field:=2, _
Criteria1:="=D"
End If
If Not IsEmpty(oldProtection) Then ' Btw, this IS how you check that oldProtection isn't null, right?
Call ProtectWithProtection(oldProtection)
End If
End If
End Sub
Private Sub ProtectWithProtection(ByRef Protect As Protection)
Worksheets("Sheet1").Protect ' ToDo: Use attributes from Protect
End Sub
此代碼位於我的Excel項目的「Sheet1」中。請注意,我正在運行Excel 2007.
因此,無論何時我設置一個變量來保存一個對象而不是一個原語,我需要使用'Set'? I.E.如果oldProtection是一個布爾值,那麼'Set'關鍵字就不是必需的了?如果那是真的,你知道這是爲什麼嗎? (就像我說的,我還在學習VBA。) – Ajedi32
是的,那是我的經驗。根據[這個答案](http://stackoverflow.com/a/349636/493055),這是設置一個對象引用(類似於C中的指針)。 –
啊,所以在VBA中使用'Set'作爲明確聲明需要創建對象引用的一種方式,所以對於像布爾值和整數這樣的基本類型不需要它,因爲它們的值將直接存儲在變量中。 – Ajedi32