Office外接程序-EXCEL(2013-2016)-VSTO-C#-事件

编辑的文件

在解决方案资源管理器>选择你的项目文件>选择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
    }
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值