2013-08-24 65 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