DISCOVER
×

How to Use VBA to Read a Microsoft Word Document

Updated July 20, 2017

Microsoft Word is a word processor program used to create and format documents. Visual Basic for Applications (VBA) is commonly used to automate repetitive tasks among Microsoft Office applications such as Word, Excel and Access. In a few steps you can write a small sub to read a Word document in VBA.

Open Microsoft Excel 2007. Click on the "Developer" tab and select "Visual Basic." Type "Sub readWordDocuemnt()" and press "Enter" to create a new sub.

Type the following to declare your variables:

Dim word Application As Word.Application

Dim word Document As Word.Document

Dim pText As String

Dim pRange As Word.Range

Dim pCount As Long

Dim rXLRow As Long

Type the following to create a new Excel workbook and open the Word document to be read:

Workbooks.Add

Set word Application = CreateObject("Word.Application")

Set word Document = wordApplication.Documents.Open("C:\Text in Word.doc")

Type the following to loop through the paragraphs in the Word document and add them to the new Excel workbook:

rXLRow = 2

With word Document

For pCount = 1 To .Paragraphs.Count

Set pRange = .Range(Start:=.Paragraphs(pCount).Range.Start, _

End:=.Paragraphs(pCount).Range.End)

pText = pRange.Text

ActiveSheet.Range("A" & rXLRow).Formula = pText

rXLRow = rXLRow + 1

Next pCount

.Close

End With

Type the following to save the new workbook, quit Word and clear variables:

wordApplication.Quit

Set word Document = Nothin:

Set word Application = Nothing

ActiveWorkbook.Saved = True

Execute the sub.

Cite this Article A tool to create a citation to reference this article Cite this Article

About the Author

Jaime Avelar is a professional writer whose programming articles appear on various websites. He has been a software programmer since 2000. Avelar holds a Master of Science in information systems from the University of Texas at Arlington.