Link to home
Start Free TrialLog in
Avatar of WonHop
WonHopFlag for United States of America

asked on

MS Word - Table Is Overwritting Previous Data

The code below adds Text and creates a Table.  The code add the text "Appendix A" & "Total items: 10"
The problem is that it will add the text.  When the table is created, it overwrites the text.
How can I add the table under/after the text?
I thought "ActiveDocument.Content.InsertParagraphAfter" would fix it.

strAppendixAName = "Appendix_A.docx"
strAppendixAPath = CurrentProject.Path
strAppendixAFullPath = strAppendixAPath & "\" & "Appendix_A.docx"

inttblAppendixAWorking =10

Dim objWord
Dim objDoc
Dim objSelection

Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Add
Set objSelection = objWord.Selection

objWord.Visible = True
objDoc.SaveAs (strAppendixAFullPath)


objSelection.TypeText ("Appendix A" & vbCrLf & "Total items:  " & inttblAppendixAWorking & vbCrLf & vbCrLf)


intRows = inttblAppendixAWorking
intCols = 2

 'Create Table
 Set tblAppA = objDoc.Tables.Add(Range:=objDoc.Range, _
                                                    NumRows:=intRows, _
tblAppA.Range.Font.Size = 12
tblAppA.Borders.Enable = True

tblAppA.Columns.PreferredWidthType = wdPreferredWidthPoints
tblAppA.Columns(1).PreferredWidth = CentimetersToPoints(3)
tblAppA.Columns(2).PreferredWidth = CentimetersToPoints(14#)
Avatar of GrahamSkan
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I guess Graham's code has a typo, it should be...

Set tblAppA = objDoc.Tables.Add(Range:=objDoc.Bookmarks("\EndOfDoc").Range, _
                                                    NumRows:=intRows, _

You can also try...

Set tblAppA = objDoc.Tables.Add(Range:=objWord.Selection.Range, _
                               NumRows:=intRows, _

Open in new window

Thanks, Neeraj.

You are, of course, correct. I typed a comma where a full stop should have been. Still understandable in text, but  fatal in a macro.

I am not currently in a position to test any code.
No problem Graham. You mentioned in your reply that you were not able to test the code at that moment and that's why I pointed that out. :)
Avatar of WonHop


Thank you guys.  That worked.  Is there a way that I can award extra points to give both of you Full Credit points?
Is there a way that I can award extra points to give both of you Full Credit points?
You can accept the Graham's answer as the Accepted Solution since he answered it first.
BTW you can award full bonus points to all the experts who you think answered your question to produce the desired output and you can also mark multiple answers as helpful. ;)
Avatar of WonHop


Thank you both for you help.  I hope I awarded the points correctly.

You're welcome! Glad we could help.