我試圖在Visual Studio 2008中爲Microsoft Word 2007創建一個C#添加項。添加內容應該在富文本內容控件中創建一個表格,以便在稍後添加一個可以重新引用該表以編輯它。我已經成功地在內容控件中創建表並重新引用內容控件來更改表內容。不幸的是,這樣做後,由於某種原因刪除了內容控制,因此我無法再引用表格。編輯表格時刪除了富文本內容控件
下面是創建該表和內容控制代碼:
private String name = "Hello";
private void btnTest1_Click(object sender, RibbonControlEventArgs e)
{
Microsoft.Office.Tools.Word.RichTextContentControl richTextControl1;
if (Globals.ThisAddIn.Application == null)
return;
Document vstoDoc = Globals.ThisAddIn.Application.ActiveDocument.GetVstoObject();
object start = Globals.ThisAddIn.Application.Selection.Start;
object end = Globals.ThisAddIn.Application.Selection.End;
object Unknown = Type.Missing;
Word.Range thisrange = Globals.ThisAddIn.Application.ActiveDocument.Range(ref start, ref end);
Word.Table oTable = vstoDoc.Tables.Add(thisrange, 2, 2,ref Unknown, ref Unknown);
oTable.Select();
richTextControl1 = vstoDoc.Controls.AddRichTextContentControl(name);
richTextControl1.Title = "Control " + name;
name += " again";
}
下面是引用內容的控制並最終將其刪除代碼:
private void btnTest2_Click(object sender, RibbonControlEventArgs e)
{
Microsoft.Office.Tools.Word.RichTextContentControl richTextControl1;
Word.Table oTable;
if (Globals.ThisAddIn.Application == null)
return;
Document vstoDoc = Globals.ThisAddIn.Application.ActiveDocument.GetVstoObject();
object Unknown = Type.Missing;
Word.ContentControls controls = vstoDoc.SelectContentControlsByTitle("Control Hello");
foreach (Word.ContentControl control in controls)
{
oTable = control.Range.Tables[1];
oTable.Cell(1,1).Range.Text = "Testing";
}
有沒有人有一個解決方案對這個問題?
我發現1,也許2,可能的解決辦法。第一種方法是在每次編輯時在表格周圍創建一個新的內容控件,並使用新的唯一名稱爲其指定相同的標題。另一個解決方法是不使用內容控件並按索引跟蹤表。這將需要一些自定義偵聽器在沒有添加的情況下創建新表時觸發事件,並且在其他方面也會非常敏感。這些解決方法都不如我希望的那樣好。 – Chris
如何在oTable.Range創建書籤並使用其名稱來定位表(在VBA中,您可以使用書籤名稱作爲書籤集合的索引,但在C#中,可能需要迭代集合才能找到它) 。 OTOH您可能會遇到與刪除書籤相似的問題。 – 2013-11-22 16:24:03