简体   繁体   中英

How to manipulate MS Word 2010 document word by word

I want to develop an MS Word 2010 Add-in (2013/2016 also) which works like a spellchecker (restores accent characters) for Turkish Text. I want to give 3 options (via context menu) to the users to use the tool.

  • fix all text in the document. (including the ones in the tables and lists etc.)
  • fix all text in a selected area
  • fix the word at the cursor position.

For the first option I tried to iterate all the words and fix them one by one by the following code:

var words = App.ActiveDocument.Words;

foreach (Range word in words)
{
    var corr = MyCorrecter(word.Text);
    word.Select();
    App.Selection.TypeText(corr);
}

However this stuck in an infinite-loop. word.Next() always returns the first word. If I remove the line word.Text = MyCorrecter(word.Text); , code iterates all the words successfully. There are find/replace examples around but those are not very efficient for this particular case.

In short, what is the most effective way to manipulate words one by one in a Word Document?

For this kind of situation - where you're actually changing the content of the target Range ("word") you need to work with a loop that "counts" with an index. For example:

Word.Words words = app.ActiveDocument.Words;
int iWordCount = words.Count;
Word.Range rngWord = null;
for (int i = 1; i<= iWordCount; i++) 
{
  rngWord = words[i]
  var corr = MyCorrecter(rngWord.Text);
  rngWord.Text = corr;
 }
//When you're done, dont' forget to release the COM objects
rngWord = null;
words = null;

I strongly recommend you do NOT use Select or Selection in your code unless what you need to do cannot be done any other way. Assign directly to the Range.Text object.

Note that there are situations in Word when it helps to run a loop backwards through the document (going from the highest counter to the lowest). I think this situation will work going forwards, however.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM