簡體   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