在VSTO Excel加载项中选择特定工作表

时间:2017-07-25 04:36:22

标签: c# vsto

我尝试使用我的excel加载项选择特定工作表(按名称或索引),但无济于事。

我的附加档案ThisAddIn.cs有:

public Excel.Workbook GetActiveWorkbook()
{
    return (Excel.Workbook)Application.ActiveWorkbook;
}

我的Ribbon1.cs有:

namespace Test3
{
    public partial class Ribbon1
    {
        private void Ribbon1_Load(object sender, RibbonUIEventArgs e)
        {
            Debug.WriteLine("Hello");
            Workbook currentwb = Globals.ThisAddIn.GetActiveWorkbook();
            Worksheet scratch = currentwb.Worksheets.Item[1] as Worksheet; // Error blocks here
            if (scratch == null)
                return;
            // Worksheet scratch = currentwb.Worksheets["Sheets1"];
            scratch.Range["A1"].Value = "Hello";
        }
    }
}

但我得到System.NullReferenceException: 'Object reference not set to an instance of an object.'

我是c#的新手(来自Python)并且非常困惑为什么这不起作用。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

问题是我在加载Workbook实例之前尝试加载它。换句话说,试图抓住Ribbon Load中的实例为时尚早。抓住ButtonClick事件上的实例工作正常!

答案 1 :(得分:0)

尝试

Excel.Application ExApp = Globals.ThisAddIn.Application as Excel.Application;

            Worksheet sheet = Globals.Factory.GetVstoObject(ExApp.ActiveWorkbook.Worksheets[1]);
            Worksheet vsheet = Globals.Factory.GetVstoObject(ExApp.ActiveWorkbook.Worksheets[2]);

            sheet.Cells[1, 1] = "A1";
vsheet.Cells[1, 1] = "A1 from second sheet";