2

テンプレートから大きなドキュメントを分割して作成しています。各テンプレートには、フッターにキーワード#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
4

2 に答える 2

1

#OVERALLPAGENUMBER#検索と置換の方法が、ループするたびにテキストを選択すると確信しています。その場合はstoryRange.Fields.Add Range:=storyRange, Type:=-1, Text:="PAGE", PreserveFormatting:=True、次のように置き換えることができます。これにより、現在の選択に必要なフィールド コードが配置されます。

Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, PreserveFormatting:=False
Selection.TypeText Text:="= 5 +"
Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, PreserveFormatting:=False
Selection.TypeText Text:="PAGE"
Selection.Fields.Update

編集: 前のコードは、PreserveFormattingが に設定されている場合にのみ機能しFalseます。PreserveFormattingが に設定されている場合、Word は空のフィールド コードを更新するようTrueです。次の方法で、選択範囲を移動して書式設定を維持できます。PreserveFormatting外側のフィールドに対してのみ必要です。

Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, PreserveFormatting:=True
Selection.MoveRight Unit:=wdCharacter, Count:=1, Extend:=wdExtend
Selection.Fields.ToggleShowCodes
Selection.MoveLeft Unit:=wdCharacter, Count:=1
Selection.MoveRight Unit:=wdCharacter, Count:=1
Selection.TypeText Text:="= 5 +"
Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, PreserveFormatting:=False
Selection.TypeText Text:="PAGE"
Selection.Fields.Update
于 2013-03-11T12:36:35.420 に答える