EXCEL VBA:别再傻傻复制粘贴啦!这串代码让你一键合并所有Word文档
- 2026-11-09 03:09:53
EXCEL VBA:别再傻傻复制粘贴啦!这串代码让你一键合并所有Word文档
📂 获取示例文件 请留言并后在台发送“合并WORD文档3”即可领取,直接拿去用!,即可获取配套示例文件 (含代码)
别再傻傻复制粘贴啦!这串代码让你一键合并所有Word文档,准时下班!
之前同大家分享过在Word里面一键合并文档的VBA代码,好多朋友都说好用。不过有读者留言问:能不能在Excel里面直接合并Word文档啊?当然可以啦!今天就来给大家安排一个Excel运行、一键合并文件夹里所有Word文档的神操作,保证你用过之后直呼“真香”!
这段代码能干啥?
你只要选一个文件夹,代码就会自动把里面所有的Word文件(.doc、.docx通通搞定)按顺序拼成一个大文档,每个文件从新的一页开始,最后保存成“合并后的文档.docx”。再也不用挨个打开、复制、粘贴,手指头都省下来啦!
操作超简单
1. 打开Excel,按 Alt+F11进入VBA编辑器。2. 插入模块(菜单:插入 → 模块)。 3. 把下面的代码直接粘贴进去。 4. 按 F5运行,选文件夹,然后……喝杯茶,等它自己搞掂!
Sub MergeWordDocsInFolder() Dim fd As FileDialog Dim strFolderPath As String Dim strFileName As String Dim wdApp As Object ' Word.Application Dim destDoc As Object ' 合并后的目标文档 Dim destRange As Object ' 目标文档中的范围 Dim i As Integer Dim bCreatedNewApp As Boolean ' 是否新建了 Word 实例 Const wdPageBreak As Long = 7 ' 分页符常量 Const wdFormatDocumentDefault As Long = 16 ' 默认 Word 文档格式 ' 选择文件夹 Set fd = Application.FileDialog(msoFileDialogFolderPicker) If fd.Show = -1 Then strFolderPath = fd.SelectedItems(1) Else MsgBox "没有选择目录。", vbExclamation Exit Sub End If If Right(strFolderPath, 1) <> "\" Then strFolderPath = strFolderPath & "\" ' 连接 Word On Error Resume Next Set wdApp = GetObject(, "Word.Application") If Err.Number <> 0 Then Set wdApp = CreateObject("Word.Application") bCreatedNewApp = True End If On Error GoTo 0 If wdApp Is Nothing Then MsgBox "无法启动 Microsoft Word,请检查安装。", vbCritical Exit Sub End If wdApp.Visible = False ' 后台运行,不弹窗 Set destDoc = wdApp.Documents.Add(Visible:=False) Set destRange = destDoc.Range(0, 0) strFileName = Dir(strFolderPath & "*.doc*") i = 0 Do While strFileName <> "" If Left(strFileName, 2) <> "~$" Then destRange.InsertFile FileName:=strFolderPath & strFileName, _ Range:="", _ ConfirmConversions:=False Set destRange = destDoc.Range(destDoc.Range.End - 1, destDoc.Range.End - 1) destRange.InsertBreak Type:=wdPageBreak Set destRange = destDoc.Range(destDoc.Range.End - 1, destDoc.Range.End - 1) i = i + 1 End If strFileName = Dir Loop If i > 0 Then destDoc.SaveAs2 FileName:=strFolderPath & "合并后的文档.docx", _ FileFormat:=wdFormatDocumentDefault destDoc.Close SaveChanges:=False MsgBox "已合并 " & i & " 个文档,保存到:" & vbCrLf & strFolderPath & "合并后的文档.docx", vbInformation Else destDoc.Close SaveChanges:=False MsgBox "文件夹中没有找到 Word 文档。", vbExclamation End If If bCreatedNewApp Then wdApp.Quit Set wdApp = Nothing Set destDoc = Nothing Set destRange = NothingEnd Sub📢 重要通知:不想错过「Excel每日一学」的每一篇干货?
由于公众号推送规则调整,“设为星标” 是确保您能准时收到我们原创内容的最佳方式。
✨ 请您花2秒完成:
点击顶部公众号名称,进入主页。
点击右上角 【…】,选择 【设为星标】。
您的👍 点赞 +
转发 +
在看,是对我们持续分享的最大支持!
感谢您阅读至此。
本文来自网友投稿或网络内容,如有侵犯您的权益请联系我们删除,联系邮箱:wyl860211@qq.com 。