VSTO Word-在任务窗格中单击按钮时添加表格行

本文关键字:按钮 添加 表格 单击 Word- 任务 VSTO | 更新日期: 2023-09-27 18:25:18

我有一个VSTO项目,单击功能区上的按钮,打开一个带有特定模板的新Word文档,并使用自定义任务窗格打开它。该窗格上有一个按钮,单击该按钮时,我想向文档模板中存在的表中添加一行。

目前,当单击任务窗格上的按钮时,我只是在运行时收到一个"命令失败"异常。这是全班同学。正如你所看到的,我尝试了两种方法,都失败了:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using word = Microsoft.Office.Interop.Word;
namespace TestWordAddin2010
{
    public partial class NewDescDMtaskPane : UserControl
    {
        public NewDescDMtaskPane()
        {
            InitializeComponent();
        }
        private void addSpare_Click(object sender, EventArgs e)
        {
            Globals.ThisAddIn.Application.ActiveDocument.Tables[1].Rows.Add(Globals.ThisAddIn.Application.ActiveDocument.Tables[1].Rows[1]);  //this doesn't work
            //word.Table wordTable = Globals.ThisAddIn.Application.ActiveDocument.Tables[1];
            //wordTable.Rows.Add(wordTable.Rows[1]);  //neither does this work
        }
    }
}

感谢您的帮助。

VSTO Word-在任务窗格中单击按钮时添加表格行

您的第一个表很可能包含合并的单元格。然后,您将无法访问Rows集合中的各个行。

作为一种变通方法,您可以使用Selection对象,如下所示:

ActiveDocument.Tables(1).Range.Select();
Application.Selection.Collapse();
Application.Selection.InsertRowsAbove();