【问题标题】:Word macro that adds the file name to the body text of a series of Word documents in a folder将文件名添加到文件夹中一系列 Word 文档的正文文本的 Word 宏
【发布时间】:2012-03-04 12:58:22
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: vba ms-word


    【解决方案1】:

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

    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
    

    【讨论】:

    • 感谢您的精彩回答!我会玩这个,看看我能不能让它工作。再次感谢!
    猜你喜欢
    • 2014-11-10
    • 1970-01-01
    • 1970-01-01
    • 2020-04-26
    • 2015-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多