Word VBA

Microsoft Office XP (Word 2002)が対象。滅多に使わないのでメモ。
[最終更新日: 2008/02/13]

1. 全体的な設定

| INDEX
Option Base 0
配列の添え字の基準値を設定できます。デフォルトでは他の言語と同じく0ベースですが、1も設定できるようです。
Option Explicit
変数を明示的に宣言するよう強制します。

2. 文書上の要素への参照を得る

| | INDEX

VBAからWordの文書上の各部品への参照を得るには、以下のようにする。

段落
ActiveDocument.Paragraphs(1)
表のセル
ActiveDocument.Tables(1).Columns(1).Cells(1)
ユーザー入力フォーム (Text入力フォーム)
ActiveDocument.FormFields("Text1")

3. 文書上に要素を追加する

| | INDEX

文書上に各部品を追加する場合。

段落
Dim p As Paragraph
Set p = ActiveDocument.Paragraphs.Add(Range:=Selection.Range)
p.Range.Text = "hello world"
Set p = Nothing
表 (選択位置に、3行4列の表を作成)
Dim tbl As Table
Set tbl = ActiveDocument.Tables.Add(Range:=Selection.Range, NumRows:=3, NumColumns:=4)
tbl.Columns(1).Cells(1).Range.Text = "hello world"
Set tbl = Nothing

4. 差込印刷のデータソースをファイルダイアログから開く

| | INDEX

以下の例では、ファイルダイアログからファイルを選び、データソース(xls)に指定する。

Dim fd As FileDialog

Set fd = Application.FileDialog(msoFileDialogFilePicker)

'ファイルダイアログの初期位置を文書のPathに設定する
fd.InitialFileName = ThisDocument.Path

If fd.Show = 0 Then
    Exit Sub
Else
    '複数ファイルが選択されていた場合でも、最初の選択ファイルが指定される
    '引数のLinkToSourceやReadOnlyの指定は随意に
    ThisDocument.MailMerge.OpenDataSource Name:=CStr(fd.SelectedItems.Item(1)), LinkToSource:=False, ReadOnly:=True
End If

Set fd = Nothing

5. 差込印刷関連の設定

| | INDEX

差込印刷に関連するコード片。

フィールドのプレビューを有効/無効にする
'プレビューを有効にする場合:
ThisDocument.MailMerge.ViewMailMergeFieldCodes = False
'プレビューを無効にする場合(フィールドコードを表示):
ThisDocument.MailMerge.ViewMailMergeFieldCodes = True
差込印刷を実行する
'MailMergeを実行:
ActiveDocument.MailMerge.Execute

細かく制御したいときなどは、一枚ずつの印刷も可能。

'Forループで回す(一枚ずつ印刷):
Dim i As Integer
With ThisDocument.MailMerge.DataSource
    For i = 1 To .RecordCount Step 1
        ThisDocument.PrintOut
    Next i
End With
差込印刷文書を通常の文書に戻す
ActiveDocument.MailMerge.MainDocumentType = wdNotAMergeDocument

6. 出力プリンタを確認する

| INDEX

以下の例では、ユーザに出力プリンタの確認を促す。

Dim res As Integer
MsgBox "現在の出力プリンタは  " & Application.ActivePrinter & "  です。"
res = MsgBox("続行しますか?", vbYesNo)
If res = vbYes Then
    'Yesの場合の処理
Else
    'そのほかの場合の処理
End If
.