什么是运行时错误91,为什么它出现在我的Excel VBA脚本中?

时间:2013-01-04 21:04:33

标签: vba excel-vba excel

好的,所以我正在尝试在VBA for Excel中编写一个简单的脚本,根据用户在电子表格的单元格中选择的某个值来更改AutoFilter。到目前为止它一直很好,但现在我收到以下错误,我无法弄清楚是什么导致它:

  

运行时错误'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。

1 个答案:

答案 0 :(得分:5)

每当VBA中有对象时,您需要使用Set运算符为其赋值。例如:

Set oldProtection = Worksheets("Sheet1").Protection