How to Use VBA to Read a Microsoft Word Document

Written by jaime avelar
How to Use VBA to Read a Microsoft Word Document
In a few steps you can set up your computer to read a Word document using VBA. (code image by Charles Taylor from Fotolia.com)

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.

Filter:
  • All types
  • Articles
  • Slideshows
  • Videos
Sort:
  • Most relevant
  • Most popular
  • Most recent

No articles available

No slideshows available

No videos available

By using the eHow.co.uk site, you consent to the use of cookies. For more information, please see our Cookie policy.