Question

I'm using a program that generates reports automatically using Word templates. In other words, I can't modify the code that preprocesses the text before read by the template.

That said, there are text entries that have a trailing newline and some that don't. I would like to remove the trailing newline if one exists.

Example: { MERGEFIELD dbEntry }

dbEntry might have a trailing newline. If it does, I'd like to remove it when displaying in the generated document using template code.

Is this possible? If not, are there any "hacks" in MS Word that I can do to make it so it "looks" like there is no newline?

Was it helpful?

Solution

Some ways to work around this include the following, but it does depend on what, if anything, you are allowed to do to the template. One thing to notice is that you may encounter text length limits of 255 characters in various places in Office applications and APIs:

a. in the special case where all the data is numeric or date, you could consider applying a numeric/date format in the field. That will, in effect, strip the trailing newline.

b. if you know that your data source supports a dialect of SQL with functions that would let you strip the newline, and you know all the field names in every data source, you could consider connecting using OpenDataSource and issuing the appropriate SQL. But beware, there is an overall limit of 511 characters in the SQL statement - 255 for some data sources. Even for text files, this may be feasible since you may be able to use the Jet/ACE text IISAM which lets you use Jet SQL. There are variations on this theme.

c. You can use the MailMerge events in the Word object model to retrieve fields from the data source as the merge proceeds. Typically, what you do then is strip the newline, insert the result into a document Variable, and use a DOCVARIABLE field to insert the result. But VBA will only retrieve the first 255 characters of the field, so if you have longer texts, you would have to be able to open the data source some other way as well, get the right text(s) from the right record, and process and insert that.

d. Insert the field data as normal, add your own unique beginning-and-end of field markers, output to a new document, and post-process.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top