Word宏将文件名添加到文件夹中的一系列Word文档的正文文本中

时间:2012-02-13 03:25:31

标签: vba ms-word word-vba

我需要一个Word宏,它将文档的文件名添加到该Word文档的第一行。但不是一次只有一个文件。我希望宏将这些文件名添加到特定文件夹中的一系列Word文档中(每个文档都有自己的文件名)。

将文件名添加到文档的宏很简单:

Selection.HomeKey Unit:=wdStory
Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, _
    Text:= "FILENAME  "
Selection.TypeParagraph

但是如何才能将文件名添加到文件夹中的整个文档系列?我想该文件夹可以在宏中命名。例如:C:\Users\username\Desktop\somefolder\。我还假设可以使用循环遍历文件夹,直到循环到达文件夹中文档的末尾。

1 个答案:

答案 0 :(得分:0)

这至少应该让你开始。我没有测试过,但我之前已经写过几次这样的东西,所以基本的想法是有效的。

Dim filePath As String
Dim thisDoc As Document
Dim wordApp As Word.Application
Set wordApp = New Word.Application

'wordApp.Visible = True ' uncomment if you want to watch things happen

'Get first file that matches
filePath = Dir("C:\Users\username\Desktop\somefolder\*.doc") ' or *.whatever
Do While filePath <> ""
    Set thisDoc = wordApp.Documents.Open(filePath)

    'Add filename at top of document
    Selection.HomeKey Unit:=wdStory
    Selection.InsertAfter filePath
    'Selection.InsertAfter ThisDocument.FullName ' alternative
    'Your way using .Fields.Add is also fine if you want the file name as 
    ' a field instead of 
    ' plain text.

    thisDoc.Close SaveChanges:=True

    'Get next file that matches and start over
    filePath = Dir()
Loop

wordApp.Quit
Set wordApp = Nothing