1. 全体的な設定
- Option Base 0
- 配列の添え字の基準値を設定できます。デフォルトでは他の言語と同じく0ベースですが、1も設定できるようです。
- Option Explicit
- 変数を明示的に宣言するよう強制します。
VBAからWordの文書上の各部品への参照を得るには、以下のようにする。
ActiveDocument.Paragraphs(1)
ActiveDocument.Tables(1).Columns(1).Cells(1)
ActiveDocument.FormFields("Text1")
文書上に各部品を追加する場合。
Dim p As Paragraph Set p = ActiveDocument.Paragraphs.Add(Range:=Selection.Range) p.Range.Text = "hello world" Set p = Nothing
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
以下の例では、ファイルダイアログからファイルを選び、データソース(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
差込印刷に関連するコード片。
'プレビューを有効にする場合: 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
以下の例では、ユーザに出力プリンタの確認を促す。
Dim res As Integer
MsgBox "現在の出力プリンタは " & Application.ActivePrinter & " です。"
res = MsgBox("続行しますか?", vbYesNo)
If res = vbYes Then
'Yesの場合の処理
Else
'そのほかの場合の処理
End If