2
votes

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.

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.

I currently have the word document open with this code:

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!

2

2 Answers

6
votes

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
0
votes

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