テンプレートから大きなドキュメントを分割して作成しています。各テンプレートには、フッターにキーワード#OVERALLPAGENUMBER#
があり、プログラムで (Excel VBA を使用して) フィールドに置き換えています。
そのドキュメントのページ番号だけが必要な場合は、次のようにすれば十分です。
Dim storyRange As Object 'Word.Range
For Each storyRange In oDoc.StoryRanges
Do
With storyRange.Find
.Text = "#OVERALLPAGENUMBER#"
.Wrap = 1 'wdFindContinue
.Execute
While .found
storyRange.Fields.Add Range:=storyRange, Type:=-1, Text:="PAGE", PreserveFormatting:=True
.Execute
Wend
End With
On Error Resume Next
Set storyRange = storyRange.NextStoryRange
On Error GoTo 0
Loop While Not storyRange Is Nothing
Next
このコードをテストしたところ、ページ番号がフッターに正常に挿入されました。ただし、必要なのは、ページ番号に固定数を追加するネストされた (式) フィールドで、複数のドキュメントにわたってページ数を表示できるようにすることです。私の解決策は、手動で(Ctrl + F9を使用して)行うと、次のようなフィールドコードが得られます。
{ = 5 + { PAGE } }
そして、1ページ目に「6」、2ページ目に「7」などを正しく生成します...
私が何をしようとしても、VBA を使用してこの種のフィールドの入れ子を複製することはできません。(ここではマクロレコーダーは役に立ちません)。これらのフィールドをプログラムで作成する方法を見つけられる人はいますか?
解決
私の問題は、PreserveFormatting:=True
あるフィールドを別のフィールドにネストしようとする試みの邪魔になることでした。これで、次の簡単なソリューションが機能します。
With storyRange.Find
.Text = "#POLICYPAGENO#"
.Wrap = 1 'wdFindContinue
.Execute
While .found
storyRange.Select
With oDoc.ActiveWindow
.Selection.Fields.Add Range:=.Selection.Range, Type:=-1, Text:="PAGE", PreserveFormatting:=False
.Selection.MoveLeft Unit:=1, Count:=1, Extend:=1
.Selection.Fields.Add Range:=.Selection.Range, Type:=-1, PreserveFormatting:=False
.Selection.TypeText Text:="= " & OverallPageNumber & " +"
End With
.Execute
Wend
End With