2012-02-13 21 views
3

文書のファイル名をそのWord文書の最初の行に追加するWordマクロが必要です。しかし、一度に1つの文書だけではありません。これらのファイル名を特定のフォルダ内の一連の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

関連する問題