1
votes

I have been writing a code to build a custom document for weekly reporting. I had it set to create a new doc, build the tables, format everything, insert a logo, etc., and I hit a wall when Word crashed every time I tried to resize the logo through VBA. It then occurred to me that I was doing this the wrong way anyway, and that I should build a template, have the code open that template, and then insert the changes directly into that document.

When I add text to the range I need, everything below is deleted. I have three lines of a header; the third line is variable and will change each week. Below that I have three tables, some cells of which will be updated each week. Right now I am just stuck at the third line of the document.

Here is an example of what I have. It is extremely short because I started anew and hit a dead end immediately.

Dim Template as Document
Set Template = ThisDocument
Dim InsertSpot as Range
Set InsertSpot = Template.Range(46)

InsertSpot.Text = "Hello"

When I run that, everything is deleted below "Hello".

I tried some different things, such as:

Set InsertSpot = Template.Range(46,50)

InsertSpot.InsertAfter "Hello"

That doesn't work; it just adds "Hello" to the first cell of the first table.

I feel silly being stuck at such an elementary part, but I honestly have no idea what to do here. Everything I looked at online talked about how to insert text at a bookmark without deleting the bookmark. I just want to enter text, period.

Any thoughts?

2

2 Answers

0
votes

I found the answer. I did the following:

Dim Template as Document
Set Template = ThisDocument
Dim InsertSpot as Range
Set InsertSpot = Template.Range(46, 46)

InsertSpot.Text = "Hello"

I had to list both the starting AND the ending character so that the inserted text would not bleed over into the rest of the page. Hope I helped someone else who is having a similar problem. Unfortunately Word VBA is pretty lacking in support and clear explanations.

0
votes

other alternatives can be

ThisDocument.Range(46).InsertBefore "Hello"

ThisDocument.Tables(1).Range.InsertBefore "Hello"

ThisDocument.Paragraphs(3).Range.InsertAfter "Hello"