MS Word在后台运行,并要求保存文件,即使它已经被保存。

问题描述 投票:0回答:1

我有一个过程,根据一个ms word模板创建一个PDF文件,其数据是从一个数据库中检索的。

它工作得很好,完美地创建了一个PDF文件,没有运行时的错误。问题是,每当我关闭计算机时,ms word就会阻止关闭,如果我按取消键,ms word就会显示一条消息。

enter image description here

代码是这样的。

   Dim wordApp As Word.Application
   Dim templateBookmarks As Word.Bookmarks
   Dim templateName As String
   Dim template As Word.Document
   'Some other variables for computations

   wordApp = CreateObject("Word.Application")
   sourceTable = New DataTable
   'Some other procs to fill the data table

   templateName = "Foo Template.docx" 
   template = wordApp.Documents.Add(templatePath & templateName)
   templateBookmarks = template.Bookmarks
   templateBookmarks.Item("sample bookmark").Range.Text = "foo"

   'Then fills the table in the template like...
   template.Tables(1).Cell(1, 1).Range.Text = dataSource.Rows(0).Item(0)

  'Then saves the document as a pdf
  Dim saveName As String = "sample file"
  template.SaveAs2(savePath & saveName, Word.WdSaveFormat.wdFormatPDF)

我试过对word COM资源强制进行垃圾回收,也试过把模板从实际文档即docx改成word模板.dotx。我也试过Quit()方法,但它只在更早的时候显示ms word消息。这是我第一次需要使用interop,所以如果我对它没有太多的想法,请原谅。

我所需要的文件都保存了,唯一的问题是ms word消息和未保存的不必要的文件,例如Document1,Document2,Document3,似乎除了所需的PDF之外,还创建了一些文件

vb.net visual-studio office-interop winforms-interop
1个回答
1
投票

使用 文件.关闭 方法,在使用PDF文件格式保存文件后关闭指定的文件。它允许指定 SaveChanges 参数,指定文档的保存操作。可以是以下参数之一 WdSaveOptions 常数。wdDoNotSaveChanges, wdPromptToSaveChangeswdSaveChanges.

On Error GoTo errorHandler 

ActiveDocument.Close SaveChanges:=wdDoNotSaveChanges

errorHandler: 
If Err = 4198 Then MsgBox "Document was not closed"
© www.soinside.com 2019 - 2024. All rights reserved.