VB.NET Word Interop Example

Open Microsoft Word documents and read their data. Use the Microsoft.Office.Interop.Word assembly.
Word. A Word DOC file can be opened in VB.NET. With the Microsoft.Office.Interop.Word assembly, we loop through all the data in the DOC. It is more difficult to use DOC files than text files. But it is possible for interoperability.

Tip: Please add the Microsoft.Office.Interop.Word assembly to your project. Go to Project -> Add Reference.

Example. The example is divided into 3 parts: the contents of the word document, the VB.NET program, and the output of the VB.NET program. In the program, we create a new Application instance.

Then: We call Documents.Open with the file name of the document specified. Next, we loop through all the words in the document.

For: We loop from the index 1 to the value of Count inclusive. The Text property from the Words collection is accessed each time.

For Each, ForConsole
Word document: word.doc One Two three VB.NET program that reads doc file Imports Microsoft.Office.Interop.Word Module Module1 Sub Main() ' Create application instance. Dim app As Application = New Application ' Open specified file. Dim doc As Document = app.Documents.Open("C:\word.doc") ' Loop through all words. Dim count As Integer = doc.Words.Count For i As Integer = 1 To count ' Write word to screen. Dim text As String = doc.Words(i).Text Console.WriteLine("Word {0} = {1}", i, text) Next ' Quit the application. app.Quit() End Sub End Module Output Word 1 = One Word 2 = Word 3 = Two Word 4 = Word 5 = three Word 6 =
Quit subroutine. Calling the Quit subroutine is important because it will end the WINWORD.EXE process. If you do not call Quit, WINWORD.EXE will stay resident in memory and will cause problems with resource usage.
Summary. It is possible to use VB.NET to programmatically read in Word documents. This works for DOC files, which use a complex format that would be hard to read yourself. Microsoft.Office.Interop.Word is therefore recommended.
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to