【发布时间】:2013-04-12 03:32:53
【问题描述】:
我正在尝试将多个 Word 文件合并为一个。我在 MS Excel 的 VBA 例程中执行此操作。 Word 文件都在一个名为“files”的文件夹中,我想在上一层的文件夹中创建一个新文件“combinedfile.docx”。我面临的问题是关于合并文件后 Word 进程的行为方式(在执行 VBA 函数后是否退出)。在某些机器上,此过程工作正常(除了它的第 2 页和最后一页为空白),而在其他一些机器上,合并的文档包含一个空白页,并且进程管理器显示由 VBA 函数启动的 Word 进程仍然正在运行。
我不习惯 VBA 编程,正如您在下面的代码中看到的那样,我不知道关闭打开的文档和退出打开的 Word 进程的正确方法。如果有人可以看看我所做的并提出解决此问题的方法,那将非常有帮助。
我也很想知道这是否是合并多个 Word 文件的正确方法。如果有更好的方法,请告诉我。
'the flow:
' start a word process to create a blank file "combinedfile.docx"
' loop over all documents in "files" folder and do the following:
' open the file, insert it at the end of combinedfile.docx, then insert pagebreak
' close the file and exit the word process
filesdir = ActiveWorkbook.Path + "\" + "files\"
thisdir = ActiveWorkbook.Path + "\"
singlefile = thisdir + "combinedfile.docx"
'if it already exists, delete
If FileExists(singlefile) Then
SetAttr singlefile, vbNormal
Kill singlefile
End If
Dim wordapp As Word.Application
Dim singledoc As Word.Document
Set wordapp = New Word.Application
Set singledoc = wordapp.Documents.Add
wordapp.Visible = True
singledoc.SaveAs Filename:=singlefile
singledoc.Close 'i do both this and the line below (is it necessary?)
Set singledoc = Nothing
wordapp.Quit
Set wordapp = Nothing
JoinFiles filesdir + "*.docx", singlefile
Sub JoinFiles(alldocs As String, singledoc As String)
Dim wordapp As Word.Application
Dim doc As Word.Document
Set wordapp = New Word.Application
Set doc = wordapp.Documents.Open(Filename:=singledoc)
Dim filesdir As String
filesdir = ActiveWorkbook.Path + "\" + "files\"
docpath = Dir(alldocs, vbNormal)
While docpath ""
doc.Bookmarks("\EndOfDoc").Range.InsertFile (filesdir + docpath)
doc.Bookmarks("\EndOfDoc").Range.InsertBreak Type:=wdPageBreak
docpath = Dir
Wend
doc.Save
doc.Close
Set doc = Nothing
wordapp.Quit
Set wordapp = Nothing
End Sub
【问题讨论】:
-
您创建了两个 Word 实例,一个在主子中,另一个在
JoinFiles()子中。他们看起来像是被正确关闭/退出。如果您制作wordApp.Visible=True并逐步通过它,JoinFiles子会发生什么? -
您希望我在哪里(在哪个语句之后)添加该语句?
-
已编辑问题:我也很想知道这是否是合并多个 Word 文件的正确方法。如果有更好的方法,我会对它感兴趣。当然,这种方法有问题:即使它有效,组合文件也有空白页(在第一个文档之后,最后)。
-
您应该添加一些错误处理,并确保如果发生任何错误,您仍在关闭和取消链接单词实例和/或文档。我有时会在没有错误处理程序的情况下打开 excel 和 word 文件时遇到类似的问题 - 他们只是提交任务管理器中的进程选项卡。