从按钮功能区访问Excel工作表

时间:2012-09-19 17:35:14

标签: c# vsto ms-office ribbon excel-addins

好的,所以我得到了自动生成的主要AddIn 附件1 ) 还有我的功能区附件2 ),我想从该功能区访问当前活动的Excel工作表。但System.Windows.Forms.Application不包含ActiveSheet的定义。

附件1:

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;
using Microsoft.Office.Tools.Excel;
using System.Windows.Forms;

namespace ExcelAddIn1
{
public partial class ThisAddIn
{
    private void ThisAddIn_Startup(object sender, System.EventArgs e)
    {

    }

    private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
    {
    }

    #region VSTO generated code

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InternalStartup()
    {
        this.Startup += new System.EventHandler(ThisAddIn_Startup);
        this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
    }
    public void doStuff()
    {

    }

    #endregion



}
}

附件2:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Tools.Ribbon;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;
using Microsoft.Office.Tools.Excel;
using System.Windows.Forms;

namespace ExcelAddIn1
{
public partial class Ribbon1
{
    private void Ribbon1_Load(object sender, RibbonUIEventArgs e)
    {

    }

    private void button1_Click(object sender, RibbonControlEventArgs e)
    {
        MessageBox.Show("Test");
        Excel.Worksheet activeWorksheet = ((Excel.Worksheet)Application.ActiveSheet);
        Excel.Range firstRow = activeWorksheet.get_Range("A1");
        firstRow.EntireRow.Insert(Excel.XlInsertShiftDirection.xlShiftDown);
        Excel.Range newFirstRow = activeWorksheet.get_Range("A1");
        newFirstRow.Value2 = "This text was added by using code";
    }
}
}

2 个答案:

答案 0 :(得分:11)

您需要从IRibbonControl.Context参数中获取RibbonControlEventArgs。此上下文代表Excel.Window。然后,您可以访问有效的Window.Application属性。

private void button1_Click(object sender, RibbonControlEventArgs e)
{
    Excel.Window window = e.Control.Context;
    MessageBox.Show("Test");
    Excel.Worksheet activeWorksheet = ((Excel.Worksheet)window.Application.ActiveSheet);
    Excel.Range firstRow = activeWorksheet.get_Range("A1");
    firstRow.EntireRow.Insert(Excel.XlInsertShiftDirection.xlShiftDown);
    Excel.Range newFirstRow = activeWorksheet.get_Range("A1");
    newFirstRow.Value2 = "This text was added by using code";
}

答案 1 :(得分:8)

如果这是VSTO Excel加载项,也许你应该使用:

   Globals.ThisAddIn.Application.ActiveSheet

问候,Jörg

相关问题