Can't edit Word 2000 document

A

Axel Dahmen

Hi,

I'm developing a VB6 project where I want to add a table with content to an
existing Word document. Somehow the code I'm writing doesn't work. The error
message I get is not very targeting (see below). Can someone please help me
out here?

This is my code (I'm referencing "Microsoft Word 9.0 Object Library"):

---------------------------------------------------------
Sub Main()
Dim wrd As Document
Dim ta As Table

Set wrd = GetObject("C:\Temp\Dok1.doc")
With wrd
Set ta = .Tables.Add(.Range(.Content.End - 1, .Content.End), _
2, 3, wdWord9TableBehavior, wdAutoFitContent)

ta.Cell(1, 1).Range.Text = "Hello" ' This yields the exception below
.Save

.Application.Quit wdDoNotSaveChanges ' Strange: Word doesn't quit.
' It's still in Task Manager
End With
End Sub
---------------------------------------------------------

I get the following error message when executing ta.Cell(1, 1).Range.Text =
"Hello":
Run time error -2147417851 (80010105) method 'Text' of object 'Range'
failed.

Moreover, if I skip the line in debugger after exception, save is performed
and changes ARE applied. Last but not least ".Application.Quit" does NOT
quit Word. It's still visible in Task Manager.

Any help is quite appreciated.

TIA,
Axel Dahmen
 
J

Jonathan West

Hi Axel,

The problem is that the Range of a Cell includes the end-of-cell marker, and
word complains when you change the Text property of that range so that the
end-of-cell marker is not there any more. You need to set the text to a
range that does not include the end-of-cell marker. Change the code as
follows

Sub Main()
Dim wrd As Document
Dim ta As Table
Dim oRange as Range

Set wrd = GetObject("C:\Temp\Dok1.doc")
With wrd
Set ta = .Tables.Add(.Range(.Content.End - 1, .Content.End), _
2, 3, wdWord9TableBehavior, wdAutoFitContent)

Set oRange = ta.Cell(1, 1).Range
oRange.MoveEnd Unit:=wdCharacter, Count:=-1
oRange.Text = "Hello"
.Save

.Application.Quit wdDoNotSaveChanges ' Strange: Word doesn't quit.
' It's still in Task Manager
End With
End Sub

The reason Word does not appear to quit is that it does quit, but because
you have a reference set to Word, a new instance is recreated.
 
A

Axel Dahmen

Thanks Jon,

I've tried your solution but with no luck... But after hours of racking my
brains I found the solution:

Set wrd = GetObject("C:\Temp\Dok1.doc")

GetObject() obviously is not OLE/ActiveX compatible. If I replace that
function call by

Dim app As New Application

Set wrd = app.Documents.Open("C:\Temp\Dok1.doc")

everything works fine...

Gosh... :/

Regards,
Axel Dahmen


-------------
 

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