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

Aje*_*i32 2 excel vba excel-vba

好的,所以我试图在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
Run Code Online (Sandbox Code Playgroud)

此代码位于我的Excel项目中的"Sheet1"内.请注意,我正在运行Excel 2007.

Kev*_*ope 5

只要VBA中有对象,就需要使用Set运算符为其赋值.例如:

Set oldProtection = Worksheets("Sheet1").Protection
Run Code Online (Sandbox Code Playgroud)

  • 这里有很好的解释http://stackoverflow.com/questions/9481140/exposing-property-as-variant-in-net-for-interop/9924325#9924325关于如何需要`Set`是因为有默认属性可用在COM对象上. (2认同)