运行时错误 91 没有意义

Posted

技术标签:

【中文标题】运行时错误 91 没有意义【英文标题】:Run-Time Error 91 doesn't make sense 【发布时间】:2014-05-22 18:34:09 【问题描述】:

这个运行时错误 91 对我来说没有意义。一般来说,问题是我没有定义一些东西,但这次我已经注意到了一切。

错误在这一行:

Set f = ThisApplication.ActiveDocument.File

ThisApplication 是在开头定义的。文件是在该行之前定义的。

这是我的代码:

Option Explicit


Public Sub ReplaceReference()

Dim invApp As Inventor.Application
Set invApp = ThisApplication

Dim NameStr As String
Dim NewNamePath As String

Dim NameStr2 As String
Dim OldNamePath As String


NameStr = Renamer.New_Name.Text               'Concatenates the full new file path
NewNamePath = Renamer.Path_Text.Text & "\" + NameStr & "-" & Right("00" & i, 3) & ".ipt"
    If Err.Number <> 0 Then MsgBox "Error Found After NewNamePath:" & Err.Description
Err.Clear

NameStr2 = Renamer.Old_Name_Display.Text      'Concatenates the old file NAME
OldNamePath = NameStr2 & "-" & Right("00" & i, 3) & ".ipt"
    If Err.Number <> 0 Then MsgBox "Error Found After OldNamePath:" & Err.Description
Err.Clear

Do While i < 99

Dim f As File
Set f = ThisApplication.ActiveDocument.File
Dim fd As FileDescriptor
    For Each fd In f.ReferencedFileDescriptors
        If fd.FullFileName = OldNamePath Then
            fd.ReplaceReference (NewNamePath)
        End If
    Next


        Loop

End Sub

我知道运行时错误 91 很常见而且看起来很愚蠢,但我就是不知道它有什么问题。

【问题讨论】:

【参考方案1】:

你能这样检查吗?那么你能确定哪个对象是 Nothing ... 也许在你的情况下是 ActiveDocument?

If ThisApplication Is Nothing Then
    Err.Raise 91, , "ThisApplication is Nothing!"
Else
    If ThisApplication.ActiveDocument Is Nothing Then
        Err.Raise 91, , "ActiveDocument is Nothing!"
    Else
        If ThisApplication.ActiveDocument.File Is Nothing Then
            Err.Raise 91, , "File is Nothing!"
        End If
    End If
End If

Dim f As File
Set f = ThisApplication.ActiveDocument.File

或者像这样(减少 if 的嵌套):

If ThisApplication Is Nothing Then
    Err.Raise 91, , "ThisApplication is Nothing!"
End If

If ThisApplication.ActiveDocument Is Nothing Then
    Err.Raise 91, , "ActiveDocument is Nothing!"
End If

If ThisApplication.ActiveDocument.File Is Nothing Then
    Err.Raise 91, , "File is Nothing!"
End If

【讨论】:

以上是关于运行时错误 91 没有意义的主要内容,如果未能解决你的问题,请参考以下文章

运行时错误“91”(对象变量或未设置块变量)

保存电子邮件附件时出现运行时错误 '91

Excel vba:.find 函数返回运行时错误 91

解决 Excel VBA 文本文件导出中的运行时 91 错误

运行时错误 91。未设置对象变量或块变量

Excel vba 运行时错误 91 对象变量或未设置块