problem reading word file...

C

Co

Hi All,

I tried a code to read the first page of a word document and save
the content to a richttextbox.
The code I created just reads the first character of the first page
instead of the first page:

Function ReadWordDocument(ByVal sPathName As String) As String

Dim wdToepassing As New Word.Application()
Dim wdDoc As Word.Document
Dim oBuiltInProps As Object
Dim strValue As String
Dim oRange As Word.Range
Dim PgDepart As Long

Try
wdDoc = wdToepassing.Documents.Open(sPathName)

'Get the Built-in Document Properties collection.
oBuiltInProps = wdDoc.BuiltInDocumentProperties
'Get the value of the Author property
strValue = oBuiltInProps.Item("Author").Value

PgDepart = wdToepassing.Selection.Range.Start

'Move the insertion pointer to the bottom of the first
page
oRange = wdDoc.Range(Start:=PgDepart, End:=PgDepart + 1)
oRange.Copy()

ReadWordDocument = _
CStr(System.Windows.Forms.Clipboard.GetDataObject.GetData
(DataFormats.Text))

Catch oException As Exception
MessageBox.Show(oException.Message)
ReadWordDocument = ""

Finally
oRange = Nothing
wdDoc = Nothing
wdToepassing.ActiveWindow.Close()
wdToepassing = Nothing
End Try

End Function

regards
Marco
The Netherlands
 
P

Pesach Shelnitz

The problem is in the following lines.

oRange = wdDoc.Range(Start:=PgDepart, End:=PgDepart + 1)
oRange.Copy()

The positions of the beginning and end of a range are measured in numbers of
characters. Thus PgDepart + 1 is the position of the second character, and
what you are seeing is expected. You can use the predefined \Page bookmark,
which embraces the entire current page, instead of your Range object. Try
replacing those two lines with this line.

wdDoc.Bookmarks("\Page").Range.Copy
 
J

Jay Freedman

Furthermore, there's no need to go through the clipboard with .Copy and
..GetDataObject. Just assign the range's .Text directly to the output string:

ReadWordDocument = wdDoc.Bookmarks("\Page").Range.Text

Besides being wasteful of processing resources, the use of the clipboard
will remove anything the user might already have placed there before the
macro started. That's an undesirable side effect.

--
Regards,
Jay Freedman
Microsoft Word MVP
Email cannot be acknowledged; please post all follow-ups to the newsgroup so
all may benefit.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top