2013-08-24 67 views
0

好的,我的主要目标是查看每个单词并检查单词是否带下划线。 如果是,我想将字体大小更改为int x。如何遍历每个单词,ms-word?

我曾尝试通过简单的每个字符会像这样 编辑:更新的代码

private void button1_Click(object sender, EventArgs e) 
    { 
     word.Application page = new word.Application(); 
     page.Visible = true; 
     word.Document doc = null; 
     foreach (string fi in listBox1.Items) 
     { 
      doc = page.Documents.Open(Application.StartupPath + "\\old\\" + fi); 
      if (doc != null) 
      { 
       int start = 0; 
       foreach (string text in doc.Range().Text.Split(" \r\n\t.".ToCharArray())) 
       { 
        int x = doc.Range().Text.IndexOf(text, start); 
        if (doc.Range(x, text.Length - 1).Underline == word.WdUnderline.wdUnderlineSingle) 
         doc.Range(x, text.Length - 1).Font = new word.Font() { Name = "Times New Roman", Bold = 4, Size = 12 }; 
        else 
         doc.Range(x, text.Length - 1).Font = new word.Font() { Name = "Times New Roman", Size = 8 }; 
        start = x+text.Length; 
       } 
      } 
     } 
     //doc.Save(); 
     // doc.Close(); 
     // page.Quit(); 
    } 

但是,我得到这个错误

呼叫由被叫方拒绝。 (异常来自HRESULT:0x80010001 (RPC_E_CALL_REJECTED))

我不知道为什么它给出了

+1

无法复制您的条件;但也许这个链接可能会有所帮助:http://stackoverflow.com/questions/9747844/getting-call-was-rejected-by-callee-exception-in-vsto-word-application – varocarbas

+0

我感谢你的帮助,但我现在已经非常接近我的答案。它通过单词循环,但我目前正在28页文档上测试它,因此需要时间才能看到结果。 – ismellike

+0

乐于阅读。如果你更好地理解确切的问题/解决方案,相应地更新你的问题(甚至可能想写你自己的答案)。如果它只是一些与正确迭代范围有关的事情(与Word自动化没有严格关联),这可能对其他人不太有用,您可以删除此问题。 – varocarbas

回答

0

这里是我的解决方案

   doc = page.Documents.Open(Application.StartupPath + "\\old\\" + fi); 
      if (doc != null) 
      { 
       for (int x = 1; x <= doc.Words.Count - 1; x++) 
       { 
         if (doc.Words[x].Underline != word.WdUnderline.wdUnderlineNone && doc.Words[x].Underline != word.WdUnderline.wdUnderlineDouble) 
          doc.Words[x].Font = new word.Font() { Name = "Times New Roman", Bold = 4, Size = 12 }; 
         else 
          doc.Words[x].Font = new word.Font() { Name = "Times New Roman", Size = 8 }; 
       } 

它精美的作品,但唯一的问题是,弹出窗口阻止代码继续执行

+0

弹出窗口说什么以及哪一行提示它? – dotNET

+0

顺便说一句,你应该考虑在循环外创建字体对象。 – dotNET

+0

这只是说我需要激活ms字,但我找到了一个解决方案。 我用for循环包围它并尝试{} catch {}循环,让人员有时间退出弹出窗口。 – ismellike

0

您的代码可能会在重大后得到改进:

doc = page.Documents.Open(System.IO.Path.Combine(Application.StartupPath, "old", fi)); 
if (doc != null) 
{ 
    word.Font RegularFont = new word.Font() { Name = "Times New Roman", Size = 12 }; 
    word.Font BigFont = new word.Font() { Name = "Times New Roman", Size = 8 }; 

    for (int x = 1; x <= doc.Words.Count; x++) 
    { 
      if (doc.Words[x].Underline != word.WdUnderline.wdUnderlineNone && doc.Words[x].Underline != word.WdUnderline.wdUnderlineDouble) 
       doc.Words[x].Font = RegularFont; 
      else 
       doc.Words[x].Font = BigFont; 
     } 
} 
+0

是的,我的回答有些过时;我改用了word.Font []数组。 – ismellike