首先简单介绍一下Excel的四大对象:Application、Workbook、Worksheet、Range。它们之间的关系如下图所示:
Application
|-------Workbook
|-------Worksheet
|--------Range
开发环境准备:Office2003或Office2007(我是以Office 2003作为学习环境的,),Visual Studio 2008。 一切准备妥当,开始动手。首先开启Visual Studio,运行”File” -->”New”-->”Project”后弹出如下图所示信息。
我选择创建Exce 2003 Add-in项目,点击OK按钮后,开发集成环境会自动生成相应代码,之后我们就可以按自己功能需求填写代码。
今天学习如何在Excel工具条中自己按钮对象和绑定事件。
[示例]
在ThisAddIn_Startup函数体中增加下列代码
Office.CommandBarButton btntest =
(Office.CommandBarButton)Application.CommandBars["Standard"].Controls.Add(
Office.MsoControlType.msoControlButton,
Type.Missing,
Type.Missing,
Type.Missing,
true);
btntest..Caption = "Button Test";
btntest.Visible = true;
btntest.Tag = "ButtonTestTag";
btntest.FaceId = 0353;
btntest.Enabled = true;
btntest.Style. = Office.MsoButtonStyle.msoButtonIcon;
btntest.Click += new Office._CommandBarButtonEvents_ClickEventHandler(btnTest_Click);
private void btnTest_Click(Microsoft.Office.Core.CommandBarButton Ctrl, ref bool CancelDefault)
{
MessageBox.Show(“Test Button Clicked!”);
}
运行程序后,显示下图所示.
点击按钮,弹出如下测试提示信息
如上述代码中:
(Office.CommandBarButton)Application.CommandBars["Standard"].Controls.Add(
修改为(Office.CommandBarButton)Application.CommandBars["cell"].Controls.Add(
按钮添加到浮动菜单中。
在把相应btntest.Click += new Office._CommandBarButtonEvents_ClickEventHandler(btnTest_Click)改为
btntest.OnAction = "testMacro", 就是调用名为testMacro的宏,由于excel文档中没有该名字的宏,故调用后出现以下提示。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/186726/viewspace-672830/ ,如需转载,请注明出处,否则将追究法律责任。