2014-11-06 55 views
0

我想弄清楚如何以編程方式將郵件合併字段插入超鏈接的word文檔中。以編程方式將郵件合併字段插入到超鏈接的word文檔

在MS Word應用程序,這是很容易用下面的代碼來實現時,在代碼視圖(ALT + F9): {HYPERLINK "http://example.com?id={MERGEFILED ID}"}

我諮詢計算器和谷歌,但就兩手空空。 我怎麼能通過C#字互操作庫來完成類似上面的代碼片段?

現在這就是我:

using mso = Microsoft.Office.Interop.Word; 
public class Test 
{ 
    public void GenerateDynamicHyperlinkWithMergeField() 
    { 
     mso.Application app = new mso.Application(); 
     object missing = System.Reflection.Missing.Value; 
     mso.Document doc = app.Documents.Add(ref missing, ref missing, ref missing, ref missing); 

     mso.Range range = app.Selection.Range; 

     // this is hyperlinked correctly 
     mso.Hyperlink hl = document.Hyperlinks.Add(range, "http://example.com?id=", ref missing, ref missing, "textToDisplay", ref missing); 

     // this mergfield is outside of hyperlink 
     mso.MailMerge merge = app.ActiveDocument.MailMerge; 
     mso.MailMergeField mf = merge.Fields.Add(range, "id"); 

     // inserts mergefield code into hyperlink, but not as recognizable code by word application 
     mso.Hyperlink hl2 = document.Hyperlinks.Add(range, "http://example.com?id=" + mf.Code.Text, ref missing, ref missing, "textToDisplay", ref missing); 
    } 
} 

任何幫助將非常感激。

更新:
澄清Word文檔中預期的結果;
我想這一點:{HYPERLINK "http://example.com?id={MERGEFILED ID}"}
但我得到這個與上面的功能:{HYPERLINK "http://example.com?id="}{MERGEFILED ID}

+0

你得到的錯誤是什麼? – BillRuhl 2014-11-06 18:25:56

+0

沒有錯誤,所有代碼都很好。只有結果不是我想要的。 我想要:{HYPERLINK「http://example.com?id={MERGEFILED ID}」}' 但我得到這個:'{HYPERLINK「http://example.com?id="}{MERGEFILED ID}' – coderock 2014-11-06 19:08:39

+0

在插入它之前,你已經嘗試了連接嗎? – BillRuhl 2014-11-06 22:59:25

回答

0

試試這個:

string myLink = "http://example.com?id=" + mf.Code.Text; 
mso.Hyperlink hl2 = document.Hyperlinks.Add(range, myString, ref missing, ref missing, "textToDisplay", ref missing); 
+0

在插入超鏈接無效之前,我嘗試了連接 – coderock 2014-11-07 11:47:46

0

這可能是一個紅色的鯡魚,但你有沒有注意到它說MERGEFILED而不是MERGEFIELD ? 我只會提起它,因爲它在所有你提到它的情況。

相關問題