如何使用VBA宏附加到Word文档

时间:2009-04-17 17:45:54

标签: vba word-vba

我正在用MS字写一个宏 我需要宏来解析文件名,页码和注释列表,并过滤掉文件名和页码。文档中的每个段落(行)都引用一个不同的文件,因此我循环使用For / Next语句。

对于每个新行,我将提取文件名和pagenumbers并将其放入字符串中。除此之外,我还在每个文件名的字符串中添加了一些注释。

在转到文档的下一行之前,我想将我构建的字符串输出到word文档中。

我目前使用此代码打开word文档:

Dim oWord as Object
Set oWord = CreateObject("Word.Application")
oWord.Documents.Open "C:\document.doc"
oWord.visible = true

这让我可以成功打开文档,但是我需要一些帮助来确定如何输出到这个文档。

从概念上讲,我知道我需要首先将其作为活动文档,然后转到文档的末尾,然后附加到它。

任何帮助将不胜感激。谢谢!

2 个答案:

答案 0 :(得分:6)

这个......更多here

Sub test()
    Dim app As Word.Application
    Dim doc As Word.Document

    Set app = CreateObject("Word.Application")
    app.Visible = True
    Set doc = app.Documents.Open("C:\test.doc")
    doc.Content.InsertAfter "Hello World"
    doc.Save
    doc.Close
    app.Quit
End Sub

答案 1 :(得分:0)

这将帮助您遍历给定目录中的文件列表

Sub ProcessDocs()
    Dim rng As Range
    Dim MainDoc As Document
    Dim strFile As String
    Const strFolder = "d:\Userfiles\yourname\testFiles\" 'change to suit
    Set MainDoc = Documents.Add
    strFile = Dir$(strFolder & "*.doc") ' can change to .docx
    Do Until strFile = ""
        'Extract your filename, pagenum here, and build a string
        'write string into the file
        strFile = Dir$()
    Loop

循环时,您可以提取文件名等; 构建你的字符串并将其写入文件。 我希望它有所帮助