Microsoft Wordを読み込んでみよう
Imports Microsoft.Office.Interop Imports System.Runtime.InteropServices.Marshal --- Dim oWord As Word.ApplicationClass 'Start Word and open the document. oWord = CreateObject("Word.Application") oWord.Visible = True oWord.Documents.Open ("C:\Doc1.doc") 'Run the macros. oWord.Run ("DoKbTest") oWord.Run("DoKbTestWithParameter", "Hello from VB .NET Client") 'Quit Word. oWord.Quit() ReleaseComObject (oWord) oWord = NothingVisual Basic .NET からオートメーションを使用して Office マクロを実行する方法
これを参考にして、Wordで表組みされた情報を取得する。
Imports Microsoft.Office.Interop Imports System.Runtime.InteropServices.Marshal --- Dim oWord As Word.ApplicationClass 'Start Word and open the document. oWord = CreateObject("Word.Application") oWord.Visible = True Dim wDoc As Word.Document wDoc = oWord.Documents.Open("F:\test\185.doc") For Each wTable As Word.Table In wDoc.Tables For Each wCell As Word.Cell In wTable.Range.Cells Console.WriteLine("Text= " & wCell.Range.Text & " @Row= " & wCell.RowIndex & " @Column= " & wCell.ColumnIndex) Next Next wDoc.Close(SaveChanges:=False) ReleaseComObject(wDoc) 'Quit Word. oWord.Quit() ReleaseComObject(oWord) oWord = Nothing
結果
Text= A1
・ @Row= 2 @Column= 1
ん?改行と「・」は不要だなぁ。しかし vbCrLf で Replace しても取れない・・・
それに、Textで取ってくると必ず末尾にvbCr(改行コード、0x0d)等がついてくるはずです。
ワードのVBAで - Visual Basic - 教えて!goo
調べてみると、最後に0x0d,0x07がくっついて「・」になっているようです。
という訳で vbCr で改行を削除し、 Chr(7) で「・」を削除できるそうだ。
Imports Microsoft.Office.Interop Imports System.Runtime.InteropServices.Marshal --- Dim oWord As Word.ApplicationClass 'Start Word and open the document. oWord = CreateObject("Word.Application") oWord.Visible = True Dim wDoc As Word.Document wDoc = oWord.Documents.Open("F:\test\185.doc") Dim temStr As String For Each wTable As Word.Table In wDoc.Tables For Each wCell As Word.Cell In wTable.Range.Cells temStr = Replace(wCell.Range.Text, vbCr & Chr(7), String.Empty) Console.WriteLine("Text= " & temStr & " @Row= " & wCell.RowIndex & " @Column= " & wCell.ColumnIndex) Next Next wDoc.Close(SaveChanges:=False) ReleaseComObject(wDoc) 'Quit Word. oWord.Quit() ReleaseComObject(oWord) oWord = Nothing
結果
Text= A1 @Row= 2 @Column= 1
おまけ・・・ドキュメントの新規作成
NewWDoc = oWord.Documents.Add '新しいドキュメントを作成 '処理 NewWDoc.SaveAs("F:\test\test.doc") 'フルパスに保存 NewWDoc.Close(SaveChanges:=False) 'ドキュメントを閉じる