• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 889
  • Last Modified:

Word VBA - read a specific line number

With VBA, I'm trying to read a specific line number in a Word document.  See code snippet below.
What do i need to include to read a specific line number?  For example, how do I change the code to read from line 11 in the Word document and store to variable "strText"

Also need to be able to specify a particular page.  So page 2, line 11.

Set doc = wrd.Application.Documents.Open(strFilePath)
            strText = '......code to read all of line 11'

Open in new window

1 Solution
try this

Function GetLineFromFile(lineno)
Dim fso, result, i, oStream
if fso.FileExists("C:\Test\test.doc") then
	Set oStream=fso.OpenTextFile("C:\Test\test.doc",1)
	While Not oStream.EndOfStream
		if i=lineno then
		end if
	GetLineFromFile = result

End Function

Open in new window

Are the lines created by hitting enter at the end. In that case you could use paragraphs,

strText = doc.Paragraphs(11).Range.Text

There is no text line object in Word, because what is displayed on a line depends on so many things - printer, font, etc.

However, this function should return the text for the current environment

Function GetLineNumberText(doc As Document, l As Long) As String
    Dim rng As Range
    Set rng = Selection.Range
    doc.Range(0, 0).Select
    Selection.MoveDown wdLine, l
    Selection.EndKey wdLine, wdExtend
    GetLineNumberText = Selection.Text
    rng.Select 'restore selection
End Function

Open in new window

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now