| visual basic 5.0中的简单activex dll,从而使用户从northwind数据库中获得一系列表单。只要选择表单,就可以移植包含access数据的office/9.shtml' target='_blank' class='article'>excel工作表。 excel工作表,该表包含菜单项的定制代码,从而初始化activex dll。可执行程序,该程序可以发送上述工作簿,并可检查公用资源中activex dll的新版本,如果发现存在新版本,则拷贝并注册该dll到用户的机器。 该方法的优点 我因为以下几个原因而喜欢该方法。一旦activex dll编译成功,它可以被任何activex的兼容宿主程序调用,这意味着你能够在microsoft word、inte.net explorer或者大量的应用程序中使用它们。 不同于 excel中的vba编码,那些dll一旦编译成功就再也不能为用户所修改,如果你想做一些与excel相似的工作,就必须创建并发布相应的附加项。正如前面讨论的那样,只要进行简单的visual basic编程,用户机器上的dll就能够轻易地被替换。这意味着一旦故障被发现,或者新版本开发成功,用户就可以直接升级,而再也不必经受安装整个应用程序的痛苦。 该方法的不足 最大的不足是需要在兼容宿主程序上调用该activex dll,如果你要移植excel工作表或word文档,那将不成问题。如果你要在自己编制的可执行程序或不可视的兼容宿主程序上调用该dll,那么控制将变得比较困难,换句话说,此时采用标准的可执行程序作为接口是不适合的,最好的方法是为另一个应用程序提供接口。 设计dll 为了创建接口,打开visual basic并创建一个标准的可执行项目,并将他存储在你所选定的exceldll文件夹中。为了加入excel引用,点击project>references和microsoft excel 8.0 object library。双击project explorer中的缺省form,并将之重新命名为frmmain,设定form的标题为open northwind tables,并且增加具有下列属性的控件: 为了创建access数据库和excel电子表格之间的接口,增加列表1的代码到form中。 列表1:设计dll,增加这些代码到form中以创建接口。 注释:declare the new class dim mcls_clsexcelwork as new clsexcelwork private sub cmdopentable_click() 注释:call the createworksheet method of the clsexcelwork 注释:class. mcls_clsexcelwork.createworksheet end sub private sub form_load() 注释:call the loadlistboxwithtables method. mcsl_clsexcelwork.loadlistboxwithtables end sub private sub form_unload(cancel as integer) set mcls_clsexcelwork = nothing end sub private sub lsttables_dblclick() mcls_clsexcelwork.createworksheet end sub
增加标准的模块到项目中,并将下列代码加入到该模块中: sub main() end sub 关闭该模块。 如果你从未创建过类模块,那么你就要认真对待,clsexcelwork是一个简单的类,工作一点儿也不困难。增加一个新的模块到项目中,并将之命名为clsexcelwork,同时在声明段中加入该类(列表2)。 列表2:clsexcelwork-增加新的类模块到项目中,然后在声明段中加入新类的代码。 option explicit private xlsheetname as excel.worksheet private xlobj as excel.workbook private excelwasnotrunning as boolean private declare function findwindow lib "user32" alias _ "findwindowa" (byval lpclassname as string, byval _ lpwindowname as long) as long private declare function sendmessage lib "user32" alias _ "sendmessagea" (byval hwnd as long, byval wmsg as long, _ byval wparam as long, byval lparam as long) as long 创建下述方法: public sub rundll() 注释:called from the activex container . 注释:this is the only public method . frmmain.show end sub friend sub loadlistboxwithtables() 注释:loads the listbox on the form with the name of 注释:five tables from the northwind database. with frmmain.lsttables .additem "categories" .additem "customers" .additem "employees" .additem "products" .additem "suppliers" end with end sub private sub getexcel() dim ws set xlobj = getobject(app.path & "\dlltest.xls") xlobj.windows("dlltest.xls").visible = true if err.number <> 0 then excelwasnotrunning = true end if 注释:clear err object in case error occurred. err.clear 注释:check for microsoft excel . if microsoft excel is running , 注释:enter it into the running object table. detectexcel 注释:clear the old worksheets in the workbook . xlobj.application.displayalerts = false for each ws in xlobj.worksheets if ws.name <> "sheet1" then ws.delete end if next xlobj.application.displayalerts = true end sub private sub detectexcel() const wm_user = 1024 dim hwnd as long 注释:if excel is running , this api call return its handle . hwnd = findwindow("xlmain", 0) 注释:0 means excel isn’t running . if hwnd = 0 then exit sub else 注释:excel is running so use the sendmessage api function to 注释:enter it in the running object table . sendmessge hwnd, wm_user + 18, 0, 0 end if end sub friend sub createworksheet() dim strjetconnstring as string dim strjetsql as string dim strjetdb as string 注释:prepare excel worksheet for the querytable . getexcel xlobj.worksheets.add xlsheetname = xlobj.activesheet.name xlobj.windows("dlltest.xls").activate 注释:modify strjetdb to point to your installation of northwind.mdb. strjetdb = "c:\program files\microsoft office\office\samples\northwind.mdb" 注释:create a connection string. strjetconnstring = "odbc;" & "dbq=" & strjetdb & ";" & _ "driver={microsoft access driver (*.mdb)};" 注释:create the sql string strjetsql = "select * from " & frmmain.lsttables.text 注释:create the querytable and populate the worksheet . with xlobj.worksheets(xlsheetname).querytables.add(connection:=strjetconnstring, _ destination:=xlobj.worksheets(xlsheetname) _ .range("a1"), sql:=strjetsql) .refresh (false) end with end sub 设计工作簿 在你能够测试这些代码之前,你必须创建excel工作簿,为了达到这个目的,打开excel,并且将缺省的book1存储到自己的路径\dlltest.xsl下,该路径是你以上创建的vb项目所在的路径。 在工作簿中,打开vba编辑器并在excel菜单中选择view>toolbars>visual basic,在visual basic工具条中点击编辑按钮。增加新模块到编辑器中,并输入下述代码(列表3)。 列表3:设计工作簿-增加新模块和下述代码。 sub runexceldll() 注释:creates an instance of the new dll and calls the main method . dim x as new exceldll.clsexcelwork x.rundll end sub sub addexceldllmenu() 注释:adds a new menu item so the dll can be started. on error resume next set mymenubar = commandbars.activemenubar with mymenubar with .controls("northwind dll") .delete end with end with set newmenu = mymenubar.controls.add _ (type := msocontrolpopup, temporary :=true) newmenu.caption = "northwind dll" set ctr11 = newmenu.controls.add(type := msocontrolbutton, _ id:=1) with ctrl1 .caption = "run northwind dll" .style = msobuttoncaption .onaction = "runexceldll" end with end sub 双击microsoft excel objects中的thisworkbook,并输入以下代码: private sub workbook_beforeclose(cancel as boolean) on error resume next set x = nothing end sub private sub workbook_open() addexceldllmenu end sub 最后,保存excel workbook,此时不要试图运行该代码,因为dll还没有创建且没有设置适当的引用。 创建并引用activex dll 为了创建activex dll,关闭excel应用程序,返回到visual basic项目,并执行以下步骤: 从菜单中点击project>properties。 在project properties对话框中,选择activex dll作为项目的属性,并点击ok。在project name文本框中,输入exceldll。点击component标签并选中project compatibility。在底部的文本框中,输入exceldll.dll,以此确保新的dll与以前的版本兼容。 在project explorer中,点击名为clsexcelwork的类,并设置实例属性为5-multiuse。 点击file菜单,并选择make exceldll.dll,为了简单起见,确认你将dll保存在项目和工作表所在的文件夹中。 重新打开excel工作簿,并打开vba编辑器。 点击tools>reference。 在对话框中,点击browse,并在exceldll.dll创建时所在的文件夹中找到该文件,双击文件名。 保存工作簿。 关闭vba编辑器和工作簿。 当你重新打开工作簿,你可以点击名为northwind dll的菜单,并选择run northwind dll,这样将打开dll接口,选择某个表格名,并点击open table按钮。如果所有的事情都处理得正确,dll将移植你所选中的工作表中的数据。 设计启动程序 需要冷静思考的是,用户是否需要打开特定的excel工作表以访问该接口?如果你需要改变用户的接口时将会发生什么?你是否需要重新编制安装文件,是否需要与每一个用户取得联系,并使他们重新安装相应的应用程序,把activex dll自动地拷贝和注册到用户的机器上是否是一种好的方法? 可执行程序能够检查dll而且在需要的时候更新并注册dll,接着继续发送execl并打开你所创建的工作簿,幸运的是,这是一种相当直接的过程。开始创建一个新个visual basic项目并将之命名为runexceldll,并删除缺省的form,再增加一个新模块到basmain。增加下列代码到模块的声明段: option explicit private excelwasnotrunning as boolean private declare function findwindow lib "user32" alias _ "findwindowa" (byval lpclassname as string , byval _ lpwindowname as long ) as long private declare function regmyserverobject lib _ "exceldll.dll" alias "dllregisterserver" () as long private declare function shellexecute lib "shell32.dll" _ alias "shellexecutea" (byval hwnd as long , byval _ lpszop as string , byval lpszfile as string , byval _ lpszparams as string , byval lpszfile as string , byval _ fsshowcmd as long ) as long 增加列表4的代码到模块中。 列表4:编制启动程序--在模块中添加下列代码。 private function registerdll() as boolean on error goto err_dll_not_registered dim regmydllattempted as boolean ‘attempt to register the dll. regmyserverobject registerdll = true exit function err_dll_not_registered: ‘check to see if error 429 occurs . if err.number = 429 then ‘regmydllattempted is used to determine whether an ‘attempt to register the activex dll has already been ‘attempted. this helps to avoid getting stuck in a loop if ‘the activex dll cannot be registered for some reason . regmydllattempeted = true msgbox " the new version of exceldll could not be _ registered on your system! this application will now _ terminate. ", vbcritical, "fatal error" else msgbox "the new version of exceldll could not be _ registered on your system. this may occur if the dll _ is loaded into memory. this application will now _ terminate . it is recommended that you restart your _ computer and retry this operation.", vbcritical, _ "fatal error". end if registerdll = false end function sub main() dim x if updatedll = true then doshellexecute (app.path & "\dlltest.xls") ‘ frmodbclogon.show vbmodal else msgbox "the application could not be started !", _ vbcritical , "error" end if end end sub sub doshellexecute(strapppath as string) on error goto codeerror dim res dim obj as object res = shellexecute(0, "open", strapppath, _ vbnullstring, curdir$, 1) if res<32 then msgbox "unable to open dlltest application" end if codeexit exit sub codeerror: megbox "the following error occurred in the procedure " & _ strcodename & chr(13) & err.number & " " & _ err.description, vbokonly, "error occurred" goto codeexit end sub function updatedll() as boolean on error goto err dim regfile if cdate(filedatetime(app.path & "\excel.dll")) <_ cdate(filedatetime("c:\temp\exceldll.dll")) then if detectexcel = true then msgbox "your version of exceldll needs to be updated, _ but microsoft excel is running. please close excel and _ restart this application so all files can be _ replaced", vbok, "close excel" end end if if msgbox("your version of exceldll is out of date, _ if you click on ok it will be replaced with the newest _ version. otherwise the application will terminate", _ vbokcancel, "replace version?") = vbcancel then end end if if dir(app.path & "\exceldll.dll") > "" _ then kill app.path & "\exceldll.dll" filecopy "c:\temp\exceldll.dll", _ app.path & "\exceldll.dll " if registerdll = true then updatedll = true exit function else updatedll = false exit function end if else updatedll = true end if exit function err: megbox "the error " & err.number & "" & _ err.description & "occurred" updatedll =false end function private function detectexcel() as boolean ‘ procedure detects a running excel and registers it. const wm_user = 1024 dim hwnd as long 注释:if excel is running, this api call returns its handle. hwnd = findwindow("xlmain", 0) if hwnd = 0 then ‘0 means excel not running. detectexcel = false else detectexcel = true end if end function |