我尝试使用我的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)并且非常困惑为什么这不起作用。任何帮助将不胜感激。
答案 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";