概要
次のマクロは、複数ページの文書を個別のファイルに分割する方法を示しています。2 つのマクロでは、Microsoft Word 文書のページ プロパティまたはセクション プロパティを使用して、ドキュメントの内容を選択および移動します。このコードを使用すると、Word を表示せずに自動的に実行できます。
詳細
マイクロソフトは、この情報をプログラミング言語の使用方法の一例として提供するだけであり、市場性および特定目的への適合性を含めて、明示的にも黙示的にも、一切の保証をいたしません。この資料は、例示されているプログラミング言語やプロシージャの作成およびデバッグに使用するツールについて理解されているユーザーを対象としています。Microsoft Support 担当者は、特定のプロシージャの機能についての問い合わせにはお答えできますが、ユーザー固有の目的に合わせた機能の追加、プロシージャの作成などの内容変更は行っておりません。
ページ単位のファイル分割
次のマクロでは、一度に 1 ページのテキストをコピーしてそのテキストを新しい文書に保存します。このマクロは、事前に定義されたブックマーク "\page" および組み込みプロパティ "number of pages" を使用します。
Sub BreakOnPage()
' Used to set criteria for moving through the document by page. Application.Browser.Target = wdBrowsePage For i = 1 To ActiveDocument.BuiltInDocumentProperties("Number of Pages") 'Select and copy the text to the clipboard. ActiveDocument.Bookmarks("\page").Range.Copy ' Open new document to paste the content of the clipboard into. Documents.Add Selection.Paste ' Removes the break that is copied at the end of the page, if any. Selection.TypeBackspace ChangeFileOpenDirectory "C:\" DocNum = DocNum + 1 ActiveDocument.SaveAs FileName:="test_" & DocNum & ".doc" ActiveDocument.Close ' Move the selection to the next page in the document. Application.Browser.Next Next i ActiveDocument.Close savechanges:=wdDoNotSaveChanges End Sub
セクション単位のファイル分割
次のマクロでは、一度に 1 セクションのテキストをコピーしてそのテキストを新しい文書に保存します。このマクロは、事前に定義されたブックマーク "\section" を使用して新しい文書を作成します。このマクロは、差し込み印刷 "新規文書へ差し込み" ファイルを分割する場合に役立ちます。
Sub BreakOnSection()
' Used to set criteria for moving through the document by section. Application.Browser.Target = wdBrowseSection 'A mail merge document ends with a section break next page. 'Subtracting one from the section count stop error message. For i = 1 To ((ActiveDocument.Sections.Count) - 1) 'Note: If a document does not end with a section break, 'substitute the following line of code for the one above: 'For I = 1 To ActiveDocument.Sections.Count 'Select and copy the section text to the clipboard. ActiveDocument.Bookmarks("\Section").Range.Copy 'Create a new document to paste text from clipboard. Documents.Add Selection.Paste ' Removes the break that is copied at the end of the section, if any. Selection.MoveUp Unit:=wdLine, Count:=1, Extend:=wdExtend Selection.Delete Unit:=wdCharacter, Count:=1 ChangeFileOpenDirectory "C:\" DocNum = DocNum + 1 ActiveDocument.SaveAs FileName:="test_" & DocNum & ".doc" ActiveDocument.Close ' Move the selection to the next section in the document. Application.Browser.Next Next i ActiveDocument.Close savechanges:=wdDoNotSaveChanges End Sub
注 : このコードを使用して文書のテキスト コンテンツを選択およびコピーする場合、ヘッダーおよびフッターは維持されません。メイン ファイルと新しい文書のテンプレートが異なる場合は、スタイル、フォントおよびレイアウトは変更される可能性がありますが、直接の書式設定は維持されます。
この資料に記載されているサンプル コードの使用方法の関連情報を参照するには、以下の「サポート技術情報」 (Microsoft Knowledge Base) をクリックしてください。290140 サポート技術情報の Office XP プログラム用のサンプル コードを実行する方法