2

好的,所以我正在尝试在 VBA for Excel 中编写一个简单的脚本,该脚本会根据用户在电子表格的单元格中选择的某些值来更改自动筛选。到目前为止,它一直运行良好,但现在我收到以下错误,我无法弄清楚是什么原因造成的:

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

4

1 回答 1

5

每当您在 VBA 中有一个对象时,您都需要使用Set运算符为其分配一个值。例如:

Set oldProtection = Worksheets("Sheet1").Protection
于 2013-01-04T21:23:42.193 回答