尝试激活文档时出现运行时错误 4160

Runtime error 4160 when trying to activate a document

提问人:Donald Ray 提问时间:11/7/2023 最后编辑:Scott CranerDonald Ray 更新时间:11/7/2023 访问量:46

问:

我正在编写一个宏来将文本从一个文档复制到另一个文档。 以下 VBA 代码创建名为“temp.com”的文件 InFileName 包含有效的路径和文件名。 当代码尝试使用 Documents(InFileName) 激活源文档时。激活 我收到运行时错误 4160。请告知我做错了什么。

Dim InFileName As String
Documents.Add DocumentType:=wdNewBlankDocument
ActiveDocument.SaveAs FileName:="temp.doc", Fileformat:=wdFormatDocument
InFileName = InputBox("Enter the Book source file name.", "Book Source File")
Documents(InFileName).Activate

我为 InFileName 输入的名称是“E:\Documents\My Stuff\Books\Scanned Books\Sue Grafton\A is for Alibi\Book\Source File.docx” 字符串的输入与您看到的一样,减去引号。

我期望激活 InFileName 中指定的文档。

VBA MS-Word

评论

1赞 Tim Williams 11/7/2023
Documents("Source File.docx").Activate可以工作(假设文件已经打开),但提供完整路径不起作用。理想情况下,在调用添加的文档时,应提供完整路径。SaveAs

答:

1赞 taller 11/7/2023 #1

正如 Tim 的评论所提到的,您应该使用 .Documents("Source File.docx")

我想在某些情况下,您可能希望指定其完整路径:

  • 如果有多个已打开的具有相同名称的文档。例如,Word 同时打开“C:\myDoc.docx”和“D:\myDoc.docx”。例如,Excel 可以打开多个同名的工作簿。cancannot

  • 如果磁盘上有同一文档的多个副本,请务必知道引用的是正确的副本。完整路径有助于确保您定位到正确的文档。Documents("myDoc.docx")

请尝试。

Option Explicit

Sub GetDocObject()
    Dim oDoc As Document, InFileName As String
    InFileName = InputBox("Enter the Book source file name.", "Book Source File")
    If Len(InFileName) > 0 Then
        For Each oDoc In Documents
            If StrComp(oDoc.FullName, InFileName, vbTextCompare) = 0 Then
'                MsgBox "Found the doc."
                oDoc.Activate
                Exit Sub
            End If
        Next
        MsgBox "Can't find the doc."
    End If
End Sub

Microsoft 文档:

StrComp 函数