[英]VBA Closing a word document which has already been opened using another sub, bad file name error
I've set up code that opens a word document and closes excel, from the word document there is code to reopen excel and copy user data to a new sheet which I pull from for a form.我已经设置了打开word文档并关闭excel的代码,从word文档中有代码可以重新打开excel并将用户数据复制到我从中提取表单的新工作表中。 This whole process works perfectly, the issue is trying to close the word document once I've finished my tasks.
整个过程完美无缺,问题是在我完成任务后尝试关闭 word 文档。
I want to close the word document once I'm back in excel however everything I'm trying returns bad file name error when I try to reference the doc.一旦我回到 excel 中,我想关闭 word 文档,但是当我尝试引用文档时,我尝试的所有内容都会返回错误的文件名错误。 I know for a fact that the file path is correct.
我知道文件路径是正确的。 I also know that you cant reference the open doc the normal way you would.
我也知道您不能以正常方式引用打开的文档。 I've substituted the variable filePath for privacy reasons.
出于隐私原因,我已经替换了变量 filePath。
Here is the code from word which is executed first这是首先执行的 word 中的代码
Sub sendTableToExcel()
Dim xlApp As Excel.Application
Dim xlWb As Excel.Workbook
Dim ws As Worksheet
Dim doc As Document
Dim tbl As Table
Set doc = ThisDocument
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
Set xlWb = xlApp.Workbooks.Open(filePath)
Set ws = Sheets.Add
ws.Name = "temp"
Set tbl = doc.Tables(1)
tbl.Range.Copy
xlWb.Worksheets(ws.Name).PasteSpecial wdPasteText
ws.Visible = False
xlWb.Application.Run "pasteCopiedValuesFromRequestDocs"
xlWb.Application.Run "openRequestLanding", "Casual" //this is the where I'm trying to close the doc
Set xlWb = Nothing
Set xlApp = Nothing
Set tblRange = Nothing
Set tbl = Nothing
Set doc = Nothing
End Sub
and the sub from excel which is called from word以及从word中调用的excel中的sub
Public Sub openRequestLanding(requestType As String)
Dim wdApp As Word.Application
Dim doc As Word.Document
Set wdApp = CreateObject("Word.Application")
wdApp.Visible = True
Set doc = wdApp.Documents(filePath)
doc.Close SaveChanges:=wdDoNotSaveChanges
Set wdApp = Nothing
Set doc = Nothing
RequestLanding.RequestTypeBox.Value = requestType
RequestLanding.Show
End Sub
You will have no success in closing the document as it is not open in the instance of Word that your code references.您将无法成功关闭文档,因为它在您的代码引用的 Word 实例中未打开。 Your code in Excel needs to get the currently open instance of Word, not create a new one.
您在 Excel 中的代码需要获取当前打开的 Word 实例,而不是创建一个新实例。
Change改变
Set wdApp = CreateObject("Word.Application")
to至
Set wdApp = GetObject(, "Word.Application")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.