先日、フッターにページ番号を入れるマクロ
を紹介しました。
今度は、ヘッダーにファイル名を入れるマクロです。
▼このマクロでできること
セクション1のヘッダーにファイル名を挿入します。
右揃えにします。
▼マクロの解説
ファイル名のフィールドをタイプで指定しています。
▼マクロ1
Sub ヘッダーにファイル名を入れる1()
Dim myRange As Range
Set myRange = ActiveDocument.Sections(1). _
Headers(wdHeaderFooterPrimary).Range
With myRange
'ファイル名の挿入(フィールド)
.Fields.Add Range:=myRange, _
Type:=wdFieldFileName, _
PreserveFormatting:=False '更新時に書式保持しない
'右揃え
.Paragraphs.Alignment = wdAlignParagraphRight
End With
Set myRange = Nothing
End Sub
▼マクロ2の解説
具体的なフィールドコードを入力しています。
▼マクロ2
Sub ヘッダーにファイル名を入れる2()
Dim myRange As Range
Set myRange = ActiveDocument.Sections(1). _
Headers(wdHeaderFooterPrimary).Range
With myRange
'ファイル名の挿入(フィールド)
.Fields.Add Range:=myRange, _
Type:=wdFieldEmpty, _
Text:="FileName", _
PreserveFormatting:=False '更新時に書式保持しない
'右揃え
.Paragraphs.Alignment = wdAlignParagraphRight
End With
Set myRange = Nothing
End Sub
▼マクロ3の解説
フィールドを使わずに、テキストで入力しています。
ActiveDocument.Name を使えばファイル名を取得できます。
▼マクロ3
Sub ヘッダーにファイル名を入れる3()
Dim myRange As Range
Set myRange = ActiveDocument.Sections(1). _
Headers(wdHeaderFooterPrimary).Range
With myRange
'ファイル名の挿入(テキスト)
.Text = ActiveDocument.Name
'右揃え
.Paragraphs.Alignment = wdAlignParagraphRight
End With
Set myRange = Nothing
End Sub
▼関連記事
フッターにページ番号を入れるマクロ