【发布时间】:2019-03-27 14:05:56
【问题描述】:
标题可能有点血腥,但我们来了。
目前我有一个 word 文档,它使用邮件合并从 Excel 工作表中插入两个属性(日期和名称)。生成合并后,我就有一个宏将结果文档的每一页拆分为它自己的单独文档。我使用的宏只是从VBA Express here 复制和粘贴的,如下所示。
Sub SplitIntoPages()
Dim docMultiple As Document
Dim docSingle As Document
Dim rngPage As Range
Dim iCurrentPage As Integer
Dim iPageCount As Integer
Dim strNewFileName As String
Application.ScreenUpdating = False 'Makes the code run faster and reduces screen _
flicker a bit.
Set docMultiple = ActiveDocument 'Work on the active document _
(the one currently containing the Selection)
Set rngPage = docMultiple.Range 'instantiate the range object
iCurrentPage = 1
'get the document's page count
iPageCount = docMultiple.Content.ComputeStatistics(wdStatisticPages)
Do Until iCurrentPage > iPageCount
If iCurrentPage = iPageCount Then
rngPage.End = ActiveDocument.Range.End 'last page (there won't be a next page)
Else
'Find the beginning of the next page
'Must use the Selection object. The Range.Goto method will not work on a page
Selection.GoTo wdGoToPage, wdGoToAbsolute, iCurrentPage + 1
'Set the end of the range to the point between the pages
rngPage.End = Selection.Start
End If
rngPage.Copy 'copy the page into the Windows clipboard
Set docSingle = Documents.Add 'create a new document
docSingle.Range.Paste 'paste the clipboard contents to the new document
'remove any manual page break to prevent a second blank
docSingle.Range.Find.Execute Findtext:="^m", ReplaceWith:=""
'build a new sequentially-numbered file name based on the original multi-paged file name and path
strNewFileName = Replace(docMultiple.FullName, ".doc", "_" & Right$("000" & iCurrentPage, 4) & ".doc")
docSingle.SaveAs strNewFileName 'save the new single-paged document
iCurrentPage = iCurrentPage + 1 'move to the next page
docSingle.Close 'close the new document
rngPage.Collapse wdCollapseEnd 'go to the next page
Loop 'go to the top of the do loop
Application.ScreenUpdating = True 'restore the screen updating
'Destroy the objects.
Set docMultiple = Nothing
Set docSingle = Nothing
Set rngPage = Nothing
End Sub
但是,邮件合并有超过 90 页,如上面的代码所示,它们都是通过在文件名末尾添加数字来命名的。而不是这个,我想拥有它,以便它从每个页面读取合并的 Date 属性并将其用作文件名。我试过修改代码并在 MS 开发中心阅读它,但我没有运气。
有人可以帮忙吗?谢谢。
【问题讨论】:
-
这个日期属性在哪里?它是单元格中的值吗?你发现如何读取这个值了吗?您所说的名称是指工作表的名称吗?
-
我可能不太清楚,抱歉。我正在将 Excel 工作表中的两个字符串字段导入到 word 到邮件合并中 - 称为日期和名称。我所指的 Date 属性是通过邮件合并从 excel 表中拉入 word 文档的内容。当我运行合并时,我得到一个长文档。上面的代码获取每一页并使其成为自己的文档。我不想在那里使用命名约定,而是使用从邮件合并中提取的日期来命名每个文档。
-
您发现如何引用此日期合并字段了吗?一旦你可以获得它的值,你就可以使用它来为 strNewFileName 赋值。
-
我正在处理 MS Office 开发中心中的内容,但我很难让它正常工作。我可以看到如何分配一个合并字段,但我不知道如何在不完全破坏代码的情况下让它随着每个页面的变化而变化。
-
有两种基本方法: 1) 知道确切数据在每个页面上的位置,以便代码可以将其作为循环的一部分来获取。 2)不要使用邮件合并;使用自动化为 Excel 中的每条记录创建每个文档(Word VBA 读取 Excel 工作表或 Excel 写入 Word)。 (2) 有很多例子;这里没有人可以为您提供 (1) 方面的帮助,因为我们不知道邮件合并结果页面的结构/页面上的日期。