我需要做的是复制一个段落并将其粘贴到一个新文件中,保存该文件,然后让它自动为下一个段落执行相同的操作。我的代码只做了一次。但是,我的文档有250页长,超过300个副页,所以我需要它自动循环。到目前为止,我的代码如下:
Sub clicktest()
'
' clicktest Macro
'
'
Selection.MoveDown Unit:=wdParagraph, Count:=34, Extend:=wdExtend
Selection.MoveDown Unit:=wdLine, Count:=2, Extend:=wdExtend
Selection.Copy
Selection.MoveLeft Unit:=wdCharacter, Count:=1
Selection.MoveDown Unit:=wdLine, Count:=37
Documents.Add DocumentType:=wdNewBlankDocument
Selection.PasteAndFormat (wdFormatOriginalFormatting)
Dim PathAndFileName As String, n As Long
PathAndFileName = "\\r04brxnas20\VHABRXOSTROR$\Trace"
If Dir(PathAndFileName & ".txt") = "" Then
ActiveDocument.SaveAs (PathAndFileName & ".txt"), FileFormat:=wdFormatText
Else
n = 1
Do While Dir(PathAndFileName & n & ".txt") <> ""
n = n + 1
Loop
ActiveDocument.SaveAs PathAndFileName & n & ".txt"
End If
End Sub我遇到的问题是循环这段代码,让活动文档成为原始文档,这样它就会自动选择正确的段落。
发布于 2014-08-05 02:36:00
在Paragraphs集合上执行一个简单的循环可能会起作用。
此外,由于您似乎只关心创建纯文本输出文件,因此不需要Copy或Paste任何东西,实际上甚至不需要使用新的Document,所有这些都可以使用标准I/O语句来完成。
这是一种方法,我还整理了命名为convent & loop文件,该文件在我尝试时出现了错误。
Sub copyparagraphs2()
Dim pg As Paragraph
Dim doc As Document
Dim ff As Integer
Dim Path As String, n As Long
Dim filename As String
Path = "\\r04brxnas20\VHABRXOSTROR$\Trace\"
Set doc = ActiveDocument
'# Loop over the PARAGRAPHS in this document
For Each pg In doc.Paragraphs
'# Construct a file path that doesn't already exist:
Do While Not Dir(Path & n & ".txt") = ""
n = n + 1
Loop
'# specify the filename
filename = n & ".txt"
'# Create the text file
CreateObject("Scripting.FileSystemObject").CreateTextFile (Path & filename)
'# print the text to the text file
ff = FreeFile
Open Path & filename For Output As #ff
Print #ff, pg.Range.Text
Close ff
Next
End Sub这就避免了担心哪个文档完全是Active还是Selection。
这是一篇关于尽可能避免选择/激活的原因的相关阅读。它是为Excel编写的,在Excel中,Selection对象比在Word中更容易避免使用,但也适用相同的一般原则。
https://stackoverflow.com/questions/25125197
复制相似问题