Click here to Skip to main content
15,042,397 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:

I want to insert some text in word document at caret position using c#.
But my program is inserting at starting position. Will it possible to insert text at desired location in opened word document?
Can anyone help on this....
Here is my code snippet.

Object oTrue = true;
Object oFalse = false;
Object readOnly = false;
Object OpenAndRepair = true;
Object oMissing = System.Reflection.Missing.Value;
Object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */
Word.Application wordApp = new Word.Application();
Word.Document wordDoc = new Word.Document();
wordApp.Visible = true; ;

object fileName = @"D:\Sample.doc";
//Opening Word Document

wordApp.Documents.Open(ref fileName,
                        ref oMissing, ref readOnly, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

Word.Selection currentSelection = wordApp.Selection;

if (currentSelection.Type == Word.WdSelectionType.wdSelectionIP)
    currentSelection.TypeText("Inserting at insertion point. ");

//Insert a paragraph at the end of the document.
Word.Paragraph oPara2;
object oRng = wordDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
oPara2 = wordDoc.Content.Paragraphs.Add(ref oRng);
oPara2.Range.Text = "Heading 2";
oPara2.Format.SpaceAfter = 6;
currentSelection.t("Inserting at insertion point$. ");

Updated 19-Apr-10 3:45am

1 solution

Your code is working exactly as it should. In order for you to insert text at a given position, you have to actually tell Word where that position is.

Your code doesn't do's what you're doing.

You open the Word document. (By default, the caret will be at the first position...or "starting" position as you said).

Then, you grab the current selection. (But again, you've not told Word to change the caret position, therefore, the current selection has a length of 0 and a position in the text of 0).

Then, you insert text at that current selection (which we've just said was at the starting point).

Of course it's possible to insert text at a given position in the text. You just have to tell it where to start.

Have a look at this: Word Object Model Overview[^]

You can do that through Selection.SetRange method

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900