[英]How can I close a file created with Word.SaveAs2 method?
我正在運行Visual Studio 2015社區,Visual Basic。 我正在引用Microsoft.Office.Interop.Word
。
下面的代碼通過使用帶有PDF參數的Doc.SaveAs2
方法轉換簡單的Word文件來創建PDF文件。
我的問題是,當我稍后嘗試在應用程序中刪除PDF文件時,它告訴我它仍在使用中。
看來我應該要做的就是關閉文件,但是我不確定該怎么做。 下面的代碼關閉Word文檔,而不關閉PDF。 我嘗試使用FileClose()
方法,但它僅接受整數作為參數。
我已經嘗試了沒有值的1和2,但是我仍然得到了
“文件正在使用中”
我嘗試刪除它時出錯。
我是VB編碼的新手,希望能對您有所幫助。
Private Sub CreateTitlePage()
Dim wdApp As Microsoft.Office.Interop.Word.Application = New Microsoft.Office.Interop.Word.Application
Dim wdDoc As Microsoft.Office.Interop.Word.Document = New Microsoft.Office.Interop.Word.Document
Dim wdPara1 As Microsoft.Office.Interop.Word.Paragraph
'Dim wdPage1 As Microsoft.Office.Interop.Word.Page
wdDoc.Application.Visible = False
wdDoc.PageSetup.VerticalAlignment = WdVerticalAlignment.wdAlignVerticalCenter
wdPara1 = wdDoc.Content.Paragraphs.Add
wdPara1.Range.InsertParagraphAfter()
wdPara1.Range.Text = "BINDER DOCUMENT" + vbVerticalTab + vbVerticalTab + "Created on: " + formattedDate2
wdPara1.Range.Font.Bold = True
wdPara1.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter
' The following statements save the document and close the Word application
wdDoc.SaveAs(binderNameDoc)
wdDoc.Close()
wdApp.Quit()
ConvertWordToPDF(tbProject.Text + "\", "Binder" + formattedDate, docLit)
End Sub
Public Sub ConvertWordToPDF(myPathName As String, myFileName As String, myFileExt As String)
Dim myWordName As String = myPathName + myFileName + myFileExt
Dim myPDFName As String = myPathName + myFileName + pdfLit
Dim word As Microsoft.Office.Interop.Word.Application = New Microsoft.Office.Interop.Word.Application()
Dim doc As Microsoft.Office.Interop.Word.Document = word.Documents.Open(myWordName)
Dim doc2 As PdfDocument = New PdfDocument
doc.Activate()
doc.SaveAs2(myPDFName, WdSaveFormat.wdFormatPDF)
doc.Close()
ReDim Preserve pdfArray(pdfArray.Length)
pdfArray(countConversions) = myPDFName
countConversions = countConversions + 1
End Sub
Word因維護文件鎖而臭名昭著,因此有時最好的選擇是搜索上一個會話中生成的文件,然后在下一個會話開始時將其刪除。
由於這不是VBA,也不是在進程內運行,也不是COM,因此正確釋放COM資源非常重要。 如果不這樣做,對象將不會在您期望的時候從內存中釋放出來,也不會被垃圾回收。
對於在COM區域中實例化的每個對象,都需要專門釋放它。 並且您還應該觸發垃圾回收以確保對象被完全釋放。 幾年前,安德魯·懷特查佩爾(Andrew Whitechapel)寫了一本很棒的書,介紹了如何使用.NET與Office一起工作,有關此問題的章節可在MSDN上找到: https : //msdn.microsoft.com/zh-cn/library/office/aa679807%28v=office .11%29.aspx?f = 255&MSPPError = -2147217396
簡而言之,您需要在完成對對象的聲明后,以相反的順序將每個聲明的對象顯式設置為Nothing。 所以:
wdDoc.Close()
wdApp.Quit
Set wdDoc = Nothing
Set wdApp = Nothing
'Now garbage collection
除此之外,我還注意到在您發布的代碼中,您在第二個過程ConvertWordToPDF中調用了Word.Application的完全獨立的實例。 我不確定為什么要使用第二個實例,但是同樣適用於此。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.