简体   繁体   中英

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. This whole process works perfectly, the issue is trying to close the word document once I've finished my tasks.

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. 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.

Here is the code from word which is executed first

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

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. Your code in Excel needs to get the currently open instance of Word, not create a new one.

Change

Set wdApp = CreateObject("Word.Application")

to

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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