2012-02-13 44 views
3

我需要一個Word宏,它將文檔的文件名添加到該Word文檔的第一行。但不是每次只有一個文檔。我希望宏將這些文件名添加到特定文件夾中的一系列Word文檔中(每個文檔都有自己的文件名)。Word宏將文件名添加到文件夾中一系列Word文檔的正文文本

,增加了文件名文件宏是簡單的:

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

但我怎麼能得到它的文件名添加到整個系列的一個文件夾中的文件?我想該文件夾可以在宏中命名。例如:C:\Users\username\Desktop\somefolder\。我還假設可以使用循環遍歷該文件夾,直到循環到達文件夾中文檔的末尾。

回答

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

謝謝你的偉大答案!我會玩這個,看看我能否得到它的工作。再次感謝! – Edward 2012-02-13 14:29:23