循环并选择活动文档

时间:2014-08-04 18:28:01

标签: vba word-vba

我需要做的是将一个段落副本粘贴到一个新文件中,保存该文件,然后让它自动为下一段做同样的事情。我的代码曾经这样做过。但是,我的文档长250页,有超过300个paragrpahs所以我需要这个自动循环。到目前为止,这是我的代码:

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

我遇到的问题是将其循环并将活动文档设为原始文档,以便自动选择正确的段落。

1 个答案:

答案 0 :(得分:1)

Paragraphs集合上的简单循环应该可行。

此外,由于您似乎只关心创建纯文本输出文件,因此无需CopyPaste任何内容,实际上没有必要即使使用新的Document,所有这些都可以通过标准I / O语句来完成。

这是方法,我还整理了文件命名修道院&amp;我尝试时出错的循环。

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

这样就无需担心哪个文档完全属于ActiveSelection

以下是有关为何尽可能避免选择/激活的相关说明。它是为Excel编写的,其中Selection对象比使用Word更容易避免使用,但适用相同的一般原则。

How to avoid using Select in Excel VBA macros