Hi everyone,

Here is my scenario: I'm creating a MS Word document using the Interop/Word
API. My document consists of multiple "blocks" and I need to ensure that each
block does not overflow a page. I have found multiple references to the
KeepTogether property but have not been successful at getting it to work.
Currently I am treating a document as a collection of paragraphs. In my code,
whenever I encounter a new "block", I am creating a new paragraph. I then
pull the range from the paragraph object and write out to the document until
I detect the end of the block.

// New block...
Range.InsertAfter("some text");
Range.Collapse(ref end);
Range.InsertAfter("most text");
// say I detect end of block here
Range.InsertParagraphAfter();
// repeat from top

If I try to set the KeepTogether property of a given paragraph, I get a
"invalid value for range exception"...

I'm setting the property like so:

doc.Paragraph[1].KeepTogether = 1;

I can't figure out what it is I'm doing wrong here...

Thanks for any help!

RE: Using KeepTogether for paragraph formatting by lf

lf
Fri Jul 11 15:40:01 PDT 2008

I donâ??t know the Interop/Word API but there is a chance that the following
may help you:

In VBA, the following line of code will turn on the â??Keep lines togetherâ??
option in the Paragraphs dialog box for the first paragraph in the active
document:

ActiveDocument.Paragraphs(1).Range.ParagraphFormat.KeepTogether = True

--
Regards
Lene Fredborg - Microsoft MVP (Word)
DocTools - Denmark
www.thedoctools.com
Document automation - add-ins, macros and templates for Microsoft Word


"T" wrote:

> Hi everyone,
>
> Here is my scenario: I'm creating a MS Word document using the Interop/Word
> API. My document consists of multiple "blocks" and I need to ensure that each
> block does not overflow a page. I have found multiple references to the
> KeepTogether property but have not been successful at getting it to work.
> Currently I am treating a document as a collection of paragraphs. In my code,
> whenever I encounter a new "block", I am creating a new paragraph. I then
> pull the range from the paragraph object and write out to the document until
> I detect the end of the block.
>
> // New block...
> Range.InsertAfter("some text");
> Range.Collapse(ref end);
> Range.InsertAfter("most text");
> // say I detect end of block here
> Range.InsertParagraphAfter();
> // repeat from top
>
> If I try to set the KeepTogether property of a given paragraph, I get a
> "invalid value for range exception"...
>
> I'm setting the property like so:
>
> doc.Paragraph[1].KeepTogether = 1;
>
> I can't figure out what it is I'm doing wrong here...
>
> Thanks for any help!
>