VBA Excel - Unable to open existing Word Document file

岁酱吖の 提交于 2020-06-18 05:32:54

问题


I have a simple macro that opens a Word Document using Excel. I made sure the Word Object Library is properly referenced but when running this macro it freezes after Documents.Open is called (based on me seeing where it fails in the debugger). I don't know if it is a OLE Automation Error but the macro freezes and I have to force close Excel.

Public Const Dir = "C:/Temp/"
Public Const File = "temp.docx"

Public Sub OpenFile()

Dim f As String: f = Dir & File

Dim oWord As Object, oDoc As Object
Set oWord = CreateObject("Word.Application")

Set oDoc = oWord.Documents.Open(f)
oDoc.Visible = True

End Sub

I get this message as well: (even though there is no other application open)

Is there an alternative to opening a file with Excel and how I rewrite my program?


回答1:


As requested - this is a common problem

You should change your Dir variable - that's a reserved name - and you're probably getting a Word error you can't see when you try to open that "file".

You should also change your File variable name too - that can be a reserved word too depending on references you've set

Added Comment:

With regard to it freezing - you can remove the oDoc.Visible = True statement and replace it with oWord.Visible = True BEFORE the problem statement Set oDoc = oWord.Documents.Open(f). That would popup the error indicating you had a problem with your filename



来源:https://stackoverflow.com/questions/39023091/vba-excel-unable-to-open-existing-word-document-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!