【发布时间】:2021-12-30 20:14:45
【问题描述】:
我们的 word 文档中有一个宏,它为 Mail Merge 中的每条记录导出一个 PDF。创建文档时,word 总是添加一个空白页,所以我们必须想办法删除最后一页(空白页)。我们添加了.Range(Lr - 1, TargetDoc.Range.End).Delete 行,它运行良好;但仅在 Word > 2007 中 - 当我们尝试在 Word 2007 中运行宏时,它说:
Option Explicit
Const FOLDER_SAVED As String = "F:\Postcard\" '//Makes sure your folder path ends with a backward slash
Const SOURCE_FILE_PATH As String = "G:\Laptop Data\GoaRegion.xlsm"
Sub TestRun()
Dim MainDoc As Document, TargetDoc As Document
Dim dbPath As String
Dim recordNumber As Long, totalRecord As Long
Dim Lr As Long
Set MainDoc = ActiveDocument
With MainDoc.MailMerge
'// if you want to specify your data, insert a WHERE clause in the SQL statement
.OpenDataSource Name:=SOURCE_FILE_PATH, sqlstatement:="SELECT * FROM [Goa$]"
totalRecord = .DataSource.RecordCount
For recordNumber = 1 To totalRecord
With .DataSource
.ActiveRecord = recordNumber
.FirstRecord = recordNumber
.LastRecord = recordNumber
End With
.Destination = wdSendToNewDocument
.Execute False
Set TargetDoc = ActiveDocument
With TargetDoc
Lr = .GoTo(wdGoToPage, wdGoToLast).Start
.Range(Lr - 1, TargetDoc.Range.End).Delete
End With
TargetDoc.ExportAsFixedFormat FOLDER_SAVED & .DataSource.DataFields("Voter").Value & ".pdf", exportformat:=wdExportFormatPDF
TargetDoc.Close False
Set TargetDoc = Nothing
Next recordNumber
End With
Set MainDoc = Nothing
End Sub
有什么问题吗? Word 2007 不支持.Range(Lr - 1, TargetDoc.Range.End).Delete 行吗?请指导...谢谢!
【问题讨论】:
-
使用对象模型,而不是反对它。测试范围的开始是否与范围的结束在同一部分。如果没有,则删除文档的最后一部分