利用 OLE 物件透過 VBA (Visual Basic for Application) 控制 WORD 文件

雖然 WordBasic 在 Word97 中仍能使用, 但未來 Office 系列產品應該都是
採用 VBA, 所以這裡不介紹 WordBasic 的指令.
先介紹 VBA 的常用屬性
  Application     
  ActiveWindow    作用中視窗
  ActiveDocument  作用中的文件
  Selection
  

建立建立 OLE 物件
  MsWord: Variant;
  MsWord := CreateOleObject('Word.Application');

(以下省略 MsWord.)
開啟 WORD
  Application.Visible := true; // 相當於 MsWord.WordBasic.AppShow
關閉 WORD
  Quit;
關閉作用中視窗
  ActiveWindow.Close;

文件檔案操作 
  ActiveDocument.Save;        // 儲存目前文件
  ActiveDocument.Saveas;      // 另存檔名
  ActiveDocument.Saved;       // 檔案是否已經儲存
  ActiveDocument.Close;       // 關閉目前文件
  Documents.Add;              // 開新檔 (default name)
  Documents.Add('檔名');      // 開新檔並指定檔名
  Documents.Open('檔名');     // 開啟舊檔
  Documents.Close;            // 關閉所有文件
  Documents.SaveAll;          // 儲存所有文件
列印
  PrintPreview := True;
  ActiveDocument.PrintOut;

插入文字:
  MsWord.Selection.TypeText('Hello, Word!');

書籤:
  ActiveDocument.Bookmarks.Add('書籤名稱');     // 插入書籤
  ActiveDocument.Bookmarks.Exists('書籤名稱');  // 檢查書籤是否存在
  ActiveDocument.Bookmarks.Items('書籤名稱').Select;  // 到指定的書籤
  ActiveDocument.Bookmarks.Items('書籤名稱').Delete;  // 刪除指定的書籤  

    Source: geocities.com/huanlin_tsai/faq

               ( geocities.com/huanlin_tsai)