编辑的文件
在解决方案资源管理器>选择你的项目文件>选择Excel>双击ThisAddIn.cs
在文件头部引入
using Excel = Microsoft.Office.Interop.Excel;
using System.Diagnostics;
认识InternalStartup(下面的事件绑定代码添加到这个方法里面)
private void InternalStartup()
{
this.Startup += new System.EventHandler(ThisAddIn_Startup);
this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
//这个方法是默认生成的,后面的需要插入的new事件绑定代码插入到这里来
}
工作簿/工作表/单元格事件
工作表-单元格内容变化-事件
1. 在InternalStartup方法里面插入下面的代码
this.Application.SheetChange += new Excel.AppEvents_SheetChangeEventHandler(Application_SheetChange);
2. 在任意位置插入下面的代码
void Application_SheetChange(object sh,Excel.Range Target)
{
Debug.WriteLine("单元格地址:",Target.Address);
}
工作表-删除-事件
1. 在InternalStartup方法里面插入下面的代码
this.Application.SheetBeforeDelete += new Excel.AppEvents_SheetBeforeDeleteEventHandler(Application_SheetBeforeDelete);
2.在任意位置插入下面的代码
void Application_SheetBeforeDelete(object Sh)
{
Excel.Workbook wb = Application.ActiveWorkbook;
Excel.Worksheet ws = Application.ActiveSheet;
Debug.WriteLine("被删除的工作表名称:"+ws.Name);
//注意,同时删除多个表格时,只拿到最后被激活的工作表
}
一个完整的ThisAddIn.cs+事件的文件示例
using Excel = Microsoft.Office.Interop.Excel;
using System.Diagnostics;
namespace baiwanxl
{
public partial class ThisAddIn
{
public Excel.Application Excelapp;
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
}
private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
{
}
#region VSTO 生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要修改
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InternalStartup()
{
Excelapp = Globals.ThisAddIn.Application;
this.Startup += new System.EventHandler(ThisAddIn_Startup);
this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
this.Application.SheetChange += new Excel.AppEvents_SheetChangeEventHandler(Application_SheetChange);
}
void Application_SheetChange(object sh,Excel.Range Target)
{
Debug.WriteLine("单元格地址:",Target.Address);//单元格地址
}
#endregion
}
}