Creating a new Table in Word

E

elziko

I'm trying to create a new table in word from a DataTable (sourceTable):

objDoc.tables.Add(Range:=objDoc.Range, NumRows:=sourceTable.Rows.Count,
NumColumns:=sourceTable.Columns.Count, DefaultTableBehavior:=1,
AutoFitBehavior:=0)

Where objDoc is a Word.Document. However I'm always given the error message
"The range cannot be deleted". But I'm not trying to delete a range. I'm
just trying to insert this Table at the caret position in the document.

I'd appreciate any help!
 
K

Ken Tucker [MVP]

Hi,

Try something like this. oWord is the word.application and odoc is
the word.document.

Dim rows As Integer = ds.Tables(0).Rows.Count

Dim columns As Integer = ds.Tables(0).Columns.Count

Dim qry As Word.Table 'query table object

Dim rTable As Word.Range = oWord.ActiveDocument.Content

qry = oDoc.Tables.Add(rTable, rows, columns)

For c = 1 To columns

For r = 1 To rows

Dim rngData As Word.Range = qry.Cell(r, c).Range

rngData.Text = ds.Tables(0).Rows(r - 1).Item(c - 1)

Next

Next



Ken
 
E

elziko

Thanks very much for your reply!

For compatibility reasons I am actually using late binding, so here is your
code as I am using it (the code above and below '-------------------- is
what I have added (to just ensure that the table is added to a previously
opened Word instance if once already exists):

Dim objDoc As Object
Dim objWordApp As Object
Try
objWordApp = GetObject(, "Word.Application")
Catch e As Exception
objWordApp = CreateObject("Word.Application")
objDoc = objWordApp.Documents.Add
End Try
objWordApp.DisplayAlerts = False
If objWordApp.Documents.Count < 1 Then
objWordApp.Documents.Add()
End If
objDoc = objWordApp.Documents(1)
'------------------------------------------------------------------

Dim rows As Integer = sourceTable.Rows.Count
Dim columns As Integer = sourceTable.Columns.Count
Dim qry As Object
Dim rTable As Object = objWordApp.ActiveDocument.Content
qry = objDoc.Tables.Add(rTable, rows, columns) '***
For c As Integer = 1 To columns
For r As Integer = 1 To rows
Dim rngData As Object = qry.Cell(r, c).Range
rngData.Text = sourceTable.Rows(r - 1).Item(c - 1)
Next
Next

'------------------------------------------------------------------
objWordApp.Visible = True
objWordApp.WindowState = 0
objWordApp.Activate()
objDoc = Nothing
objWordApp = Nothing

However, at runtime I still get the exception telling me that the range
cannot be deleted on the line shown with '***. Do you have any idea why this
may be happening for me and not for you?
 

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