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

Vba Word宏,将文件名添加到文件夹中一系列Word文档的正文中,vba,ms-word,Vba,Ms Word,我需要一个Word宏,将文档的文件名添加到该Word文档的第一行。但不是一次只有一份文件。我希望宏将这些文件名添加到特定文件夹中的一系列Word文档中(每个文档都有自己的文件名) 将文件名添加到文档的宏很简单: Selection.HomeKey Unit:=wdStory Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, _ Text:= "FILENAME " Selection.TypeParagra

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

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

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

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

这至少可以让您开始。我还没有测试过它,但是我以前写过几次这种类型的东西,所以基本的想法是可行的

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
将文件路径设置为字符串
将此文档设置为文档
Dim wordApp作为Word.Application
Set wordApp=New Word.Application
“wordApp.Visible=True”如果要观看事件发生,请取消注释
'获取第一个匹配的文件
filePath=Dir(“C:\Users\username\Desktop\somefolder\*.doc”)或*
在文件路径“”时执行此操作
设置thisDoc=wordApp.Documents.Open(文件路径)
'在文档顶部添加文件名
Selection.HomeKey单位:=wdStory
Selection.InsertAfter文件路径
“Selection.InsertAfter ThisDocument.FullName”备选方案
'如果您希望文件名为
“一块地,而不是
“纯文本。
thisDoc.Close SaveChanges:=True
'获取下一个匹配的文件并重新开始
filePath=Dir()
环
wordApp,退出
设置wordApp=Nothing

感谢您的精彩回答!我会玩这个,看看能不能用。再次感谢!