我想弄清楚如何以編程方式將郵件合併字段插入超鏈接的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}
你得到的錯誤是什麼? – BillRuhl 2014-11-06 18:25:56
沒有錯誤,所有代碼都很好。只有結果不是我想要的。 我想要:{HYPERLINK「http://example.com?id={MERGEFILED ID}」}' 但我得到這個:'{HYPERLINK「http://example.com?id="}{MERGEFILED ID}' – coderock 2014-11-06 19:08:39
在插入它之前,你已經嘗試了連接嗎? – BillRuhl 2014-11-06 22:59:25