【问题标题】:What is run time error 91, and why is it showing up in my Excel VBA script?什么是运行时错误 91,为什么它会出现在我的 Excel VBA 脚本中?
【发布时间】:2013-01-04 21:04:33
【问题描述】:

好的,所以我正在尝试在 VBA 中为 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。

【问题讨论】:

    标签: vba excel


    【解决方案1】:

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

    Set oldProtection = Worksheets("Sheet1").Protection
    

    【讨论】:

    • 所以每当我设置一个保存对象而不是原始的变量时,我需要使用Set? IE。如果 oldProtection 是布尔值而不是 Set 关键字,则不需要?如果这是真的,你知道为什么吗? (就像我说的,我还在学习 VBA。)
    • 是的,这就是我的经验。根据this answer,这是设置对象引用(类似于C中的指针)。
    • 啊,所以 Set 在 VBA 中用作明确说明需要创建对象引用的一种方式,因此对于布尔值和整数之类的原语不需要它,因为它们的值将是直接存储在变量中。
    • 这里很好地解释了stackoverflow.com/questions/9481140/… 关于Set 的需求是如何在 COM 对象上提供默认属性的结果。
    猜你喜欢
    • 2020-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-30
    • 2019-05-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多