繁体   English   中英

VBA关闭已经使用另一个子错误文件名错误打开的word文档

[英]VBA Closing a word document which has already been opened using another sub, bad file name error

我已经设置了打开word文档并关闭excel的代码,从word文档中有代码可以重新打开excel并将用户数据复制到我从中提取表单的新工作表中。 整个过程完美无缺,问题是在我完成任务后尝试关闭 word 文档。

一旦我回到 excel 中,我想关闭 word 文档,但是当我尝试引用文档时,我尝试的所有内容都会返回错误的文件名错误。 我知道文件路径是正确的。 我也知道您不能以正常方式引用打开的文档。 出于隐私原因,我已经替换了变量 filePath。

这是首先执行的 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

以及从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

您将无法成功关闭文档,因为它在您的代码引用的 Word 实例中未打开。 您在 Excel 中的代码需要获取当前打开的 Word 实例,而不是创建一个新实例。

改变

Set wdApp = CreateObject("Word.Application")

Set wdApp = GetObject(, "Word.Application")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM