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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/761475/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 10:23:15  来源:igfitidea点击:

How to append to a word document with VBA Macros

vbaword-vba

提问by Leejo

I am writing a macro in MS word.
I need the macro to parse through a list of filenames, page numbersm and notes and filter out only the file names and page numbers. Each paragraph (line) in the document refers to a different file, so I am looping through For/Next statement.

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

For each new line, I'm pulling out the filename, and pagenumbers and placing it into a string. Along with this, I am also adds some notes into the string for each file name.

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

Before going to the next line in the document, I want to output the string that I've built into a word document.

在转到文档的下一行之前,我想输出我已内置到 Word 文档中的字符串。

I currently have the word document open with this code:

我目前使用以下代码打开了 word 文档:

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

This lets me successfully open the document but I need some help with figuring out how to output to this document.

这让我成功打开文档,但我需要一些帮助来弄清楚如何输出到这个文档。

Conceptually, I know I need to first make it the active document, then go to the end of the document, then append to it.

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

Any help would be appreciated. Thanks!

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

回答by aintnoprophet

What about this...more 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

回答by Mehz

This will help you loop through the list of files in a given directory

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

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

While looping, you can extract the filenames, etc; build your string and write it to the file. I hope it helps

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