In my app I'm editing a word document, I want to modify some values but I want the changes to affect the first page, only:
The content of the first page is like:
USER:
COMPANY:
and I want to modify it to:
USER: aaa
COMPANY: bbb
I have tried like:
//properties
object objMiss = System.Reflection.Missing.Value;
object objEndOfDocFlag = "\\endofdoc"; /* \endofdoc is a predefined bookmark */ //Start Word and create a new document.
Microsoft.Office.Interop.Word._Application objApp;
Microsoft.Office.Interop.Word._Document objDoc;
//load the document:
objDoc = objApp.Documents.Open(@"C:\Users\BugsFixer\file.docx", ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss);
int count = objDoc.Words.Count;
for (int i = 1; i <= count; i++)
{
string text = objDoc.Words[i].Text;
if (text.StartsWith("USER"))
objDoc.Words[i].Text = "USER: aaa";
if (text.StartsWith("COMPANY"))
objDoc.Words[i].Text = "COMPANY: bbb";
}
but this woud change all "USER" strings. I need something like:
if(current page is one)
{
//replace USER with USER:aaa
//replace COMPANY with COMPANY:bbb
}
How to check that I'm editing a specific page i.e in my case page 1?
Word has an interesting method: get_Information
which takes an argument of the enumeration Word.WdInformation
. There are a number of useful things this can return, among them, the current page number of a selection or Range.
Since the Word
object returns a Range
it's possible to query the page number something like this:
Word.Range rngWord = objDoc.Words[i];
string text = rngWord.Text;
int pgNumber = rngWord.get_Information(Word.WdInformation.wdActiveEndPageNumber);
if (pgNumber = 1)
{
if (text.StartsWith("USER"))
{ //and so on
Note that it's also possible to use foreach
with the Words
collection instead of getting the count of Words in the document and using a for
loop.
All that being said, the code would probably be more efficient if it used Word's Find
functionality instead of looping word-by-word...