这个问题弄了好一段时间终于找到了。
一、创建工程: 打开VB6.0,新建一个外接程序
二、VB中添加引用:
在“工程”菜单中点击“引用”,然后选上“Microsoft Excel 11.0 Object Libray”这个选项,因为我用的是Excel2003版,其它版本的版本号就不是11.0,选择对应的即可。引用后,在代码编写过程中,就可以自动完成对象的属性、方法了。
三、设置设计器属性:
工程名称:YB_COM
四、编写代码:
1、设计器代码:
Code
Option Explicit
'加载时事件
Private Sub AddinInstance_OnConnection(ByVal Application As Object, ByVal ConnectMode As AddInDesignerObjects.ext_ConnectMode, ByVal AddInInst As Object, custom() As Variant)
Set xlApp = Application
Set ExcelEvents = New VBAclass '类模块名称
End Sub
'卸载后事件
Private Sub AddinInstance_OnDisconnection(ByVal RemoveMode As AddInDesignerObjects.ext_DisconnectMode, custom() As Variant)
Set xlApp = Nothing
Set ExcelEvents = Nothing
End Sub
2、模块代码:
Option Explicit
Public xlApp As Excel.Application
Public ExcelEvents As VBAclass '类模块名称
3、类模块代码:VBAclass
Code
Option Explicit
Public WithEvents XL As Excel.Application
Private Sub Class_Initialize()
Set XL = xlApp
MsgBox "Class_Initialize()"
End Sub
'激活单元格事件
Private Sub XL_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Excel.Range)
MsgBox "XL_SheetSelectionChange"
End Sub
'工作簿打开事件,打开第二个excel文件才触发-?
Private Sub XL_WorkbookOpen(ByVal Wb As Workbook)
MsgBox "XL_Open"
End Sub
'工作薄保存事件
Private Sub XL_WorkbookBeforeSave(ByVal Wb As Workbook, ByVal SaveAsUI As Boolean, Cancel As Boolean)
MsgBox "XL_BeforeSave"
End Sub
'工作薄关闭事件
Private Sub XL_WorkbookBeforeClose(ByVal Wb As Workbook, Cancel As Boolean)
MsgBox "XL_BeforeClose"
End Sub
五、生成Dll,注册Dll。
示例下载
参考自:http://club.excelhome.net/viewthread.php?tid=431819&page=1&extra=page%3D1#pid2800643