【发布时间】:2020-02-29 13:18:41
【问题描述】:
我有一个宏,它接受一个 Word 文档,将数据复制到我的参数中,然后将其粘贴到多个单独的文档(在本例中为三个)。
这是第一次使用VBA,所以请放轻松。
原始文档是一个长文档,有多个重复部分。通过填写原始文档,用户可以节省完成一份而不是三份几乎相同的文档的时间。我把原文分成了三个部分。我的代码从第一个声明的部分获取数据并将其粘贴到新文档中。它也适用于第三个。但是,第二个不起作用。
With R.Find
.Text = "START OF FORM*^12"
.MatchWildcards = True
部分查找文本“表格开始”并将其和其余内容直到“^12”(我认为这是指分页符)。
文档的布局使得文档的每个部分都以该文本开头并以分页符结尾。
Sub DocSplit()
' Declares variable (in this case R).
Dim R As Range
' Sets R to the active document, being a number of ranges (will be defined later).
Set R = ActiveDocument.Range.Duplicate
' You won't be able to see what the macro is doing, but will run quicker.
Application.ScreenUpdating = False
' For R, find text with whatever is in the " marks.
With R.Find
.Text = "START OF FORM*^12"
.MatchWildcards = True
' Runs a series of statements as long as given conditions are true. While it's doing this,
While .Execute
' Copy and saves contents of R.
CopyAndSave R
' While ends.
Wend
'With ends.
End With
' Collapses range to the ending point.
R.Collapse wdCollapseEnd
' Returns or sets the ending character position of a range.
R.End = R.Parent.Range.End
CopyAndSave R
End Sub
Static Sub CopyAndSave(R As Range)
' Declares D as document.
Dim D As Document
' Represents the number of words in the collection.
' Long is a datatype for values too large for "integer".
Dim Count As Long
Count = Count + 1
' Copies R from previous Sub to a new document.
R.Copy
Set D = Documents.Add
' Pastes range, preserving original formatting.
D.Range.PasteAndFormat wdFormatOriginalFormatting
D.SaveAs R.Parent.Path & Application.PathSeparator & _
"F00" & Count, wdFormatDocument
D.Close
End Sub
我确实希望创建三个文档,F001、F002 和 F003。我得到两个文件,一个包含第一部分(按预期),一个包含最后两个文件。
【问题讨论】:
-
你知道你可以做
.FormattedText= .FormattedText。因此,在文档中使用分节符会更有意义。