简体   繁体   中英

Selecting a specific sheet in VSTO Excel Add-In

I'm trying to select a specific sheet (by name or index) with my excel Add-In with no avail.

My addin file ThisAddIn.cs has:

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

And my Ribbon1.cs has:

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";
        }
    }
}

But I get a System.NullReferenceException: 'Object reference not set to an instance of an object.'

I'm new to c# (come from Python) and am very confused why this doesn't work. Any help would be greatly appreciated.

The issue was I was trying to load the Workbook instance before it was loaded. In other words, trying to grab the instance in Ribbon Load was too early. Grabbing the instance on a ButtonClick event worked fine!

Try

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";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM