ExcelVBAからWordを操作する

使用前の準備として、参照設定を行う必要があります。

Excelのメニューで、ツール→マクロ→Visual Basic Editorとして、Visual Basic Editorのメニューから、

ツール→参照設定で、「Microsoft Word 9.0 Object Library」をチェックして、OKを押します。

特定の文字列を指定して、その文字列の色を変更するプログラムは、以下のとおりです。

Sub test()
    Dim wdObj    As New Word.Application
    Dim wdDoc    As Word.Document
    Dim wordFile As String
    
    'オープンするワードのファイル名をパス名付きで入れます
    wordFile = "c:¥hoge.doc"
    
    'ワードを開きます。
    wdObj.Visible = True
    wdObj.Documents.Open wordFile
    
    '検索するキーワードを設定します。
    wdObj.Selection.Find.Text = "置換対象の文字"
    
    '検索する方向を指定します。
    wdObj.Selection.Find.Forward = True
    
    '色を指定します。
    wdObj.Selection.Find.Replacement.Font.Color = wdColorRed
    
    '検索を実行し、全てを置換します。
    wdObj.Selection.Find.Execute , , , , , , , , , , wdReplaceAll
    
    '変更を保存します。
    wdObj.ActiveDocument.Close SaveChanges:=True
    
    'ワードを閉じます。
    wdObj.Quit

End Sub

VBAのお勉強 まとめへ戻る

Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

© 2011 simple blog いろいろ勉強中 Suffusion theme by Sayontan Sinha