vbpjtip5 面向VisualBasic程序员的杂志 第5版.docx

上传人:李司机 文档编号:7146639 上传时间:2024-06-15 格式:DOCX 页数:69 大小:144.44KB
返回 下载 相关 举报
vbpjtip5 面向VisualBasic程序员的杂志 第5版.docx_第1页
第1页 / 共69页
vbpjtip5 面向VisualBasic程序员的杂志 第5版.docx_第2页
第2页 / 共69页
vbpjtip5 面向VisualBasic程序员的杂志 第5版.docx_第3页
第3页 / 共69页
vbpjtip5 面向VisualBasic程序员的杂志 第5版.docx_第4页
第4页 / 共69页
vbpjtip5 面向VisualBasic程序员的杂志 第5版.docx_第5页
第5页 / 共69页
点击查看更多>>
资源描述

《vbpjtip5 面向VisualBasic程序员的杂志 第5版.docx》由会员分享,可在线阅读,更多相关《vbpjtip5 面向VisualBasic程序员的杂志 第5版.docx(69页珍藏版)》请在三一办公上搜索。

1、WelcometotheFifthEditionoftheVBPJTechnicaltipsSupplement!ThesetipsandtricksweresubmittedbyprofessionaldevelopersusingVisualBasic3.0,VisualBasic4.0,VisualBasic5.0,VisualBasicforApplications,andVisualBasicScript.ThetipswerecompiledbytheeditorsatVisualBasicProgrammer,sJournal.SpecialthankstoVBPJTechnic

2、alReviewBoardmembersFrancescoBalenaandPhilWeberfortestingallthecode.IfyoudliketosubmitatiptoVisualBasicProgrammer,sJournal,pleasesendittoUsertips,FawcetteTechnicalPublications,209HamiltonAvenue,PaloAlto,California,USA,94301-2500.Youcanalsofaxitto415-853-0230orsenditelectronicallytoVbpjeditQor74774.3

3、050CompuS.Pleaseincludeaclearexplanationofwhatthetechniquedoesandwhyitisuseful,indicateifit,sforVBA,VBS,VB3zVB416-or32-bitzorVB5.Pleasetrytolimitcodelengthto20lines.Dontforgettoincludeyoure-mailandmailingaddress.We,11payyou$25ifwepublishyourtipVB3,VB416/321.evel:BeginningCOMBOBOXEVENTHAND1.INGTwopro

4、blemscanarisewhenaconfuseduserscrollsupordownwiththemouseandthenmakesaselectionwiththeEnterKey.First,thedownarrowfirestwoevents:ChangeandClick.Second,theEnterkeymovesfocustothenexttabstop,whilethemouseclickdoesn,tcausealossoffocusfromthecombobox.Therefore,ifyouplaceyouractioncodeintheChangeevent,anU

5、porDownarrowwillfireit,whichyoudon,twant.Onthecontrary,ifyouplaceyouractioncodeonlyinthe1.ostFocuseventandtheuserclicksonaselection,focuswon,tmovefromthecombobox,andtheuserisleftstaringattheselectedtextinthecomboboxandwonderingwhynoactionoccurred.ThissolutionfiltersoutClickeventsgeneratedwitharrowke

6、ys,andforcesthecontroltolosefocus.IntheDeclarationssectionoftheform,enterthiscode:Note:UseanIntegerflagvariablein,VB3DimbNoiseasBoolean,TruedenotesaNoiseEventwhichisto,beignoredEnterthiscodeintheForm_1.oadevent:bNoise=FalseEnterthiscodeinthecomboboxKeyDownevent:PrivateSubcbTest_KeyDown(KeyCodeAs_Int

7、eger,ShiftAsInteger),Iftheuserisbrowsingwiththe,arrows,ignoretheClickEventsIfKeyCode=VbKeyDownOrKeyCode_=VbKeyUpThenbNoise=TrueEndSubevent:EnterthiscodeinthecomboboxClickPrivateSubcbTest_Click()IfbNoiseThen,IgnoreNoiseevents,(upordownarrow)bNoise=FalseElseForcelossoffocusSendKeys”TAB”,TrueEndIfEndSu

8、bWritecodethatreactstoanewuserselectioninthecombobox1.ostFocusevent.Don,tsendaTabkeystrokebecausefocushasalreadyshifted,andthecombobox,sbehaviorisconsistentregardlessofhowtheuserselectsanewvalue.-1.esSmith,Concord,NorthCarolinaVB51.evel:BeginningCOMMENTANDUNCOMMENTB1.OCKSOFCODEVisualBasic5.0letsyouc

9、ommentablockofcodeinasnapanduncommentitlater.Thisfeatureisusefulinthedebugphase,whenyoudon,twanttoexecuteanumberofstatements,butyoudon,twanttophysicallydeletethemeither.However,theComment/Uncommentcommandpairisn,tpresentinanymenuoftheenvironment,andyoucanonlyreachitbyenablingtheEdittoolbar.Todothisq

10、uickly,right-clickonanytoolbarintheenvironmentandselecttheEditcommand.-FrancescoBalena,Bari,ItalyVB51.evel:BeginningDEFAU1.TVA1.UESFOROPTIONA1.PARAMETERSIfyoueverprogrammedunderVB4,youprobablytookadvantageofthepowerfulOptionalparameters.VB5enhancedtheminseveralways:theycanbeofanytypenow(notonlyVaria

11、nts),andtheycanappearinPropertyprocedures.Interestingly,youcannowstateadefaultvalueforthem:PropertyGetValue_(OptionalindexAs1.ong=1)EndPropertyYoucandothiswithoutanexplicit(andslower)IsMissingtest:PropertyGetValue_(OptionalindexAs1.ong)IfIsMissing(index)Thenindex=1EndProperty-FrancescoBalena,Bari,It

12、alyDON*TCREATEA1.IASEDVARIAB1.ESNeverpassaglobalvariableasanargumenttoaprocedurethatalsoaccessesthevariabledirectly.Ifyou,re100percentsureyouadheredtothisrulewithinyourapplication,checktheAssumeNoAliasingoptionintheAdvancedOptimizationsdialogthatyouinvokefromtheCompiletaboftheProjectPropertiesdialog

13、.Ifthenativecodecompilerknowsnoaliasedvariablesexist,itcanfreelycachevariablevaluesintofasterCPUregisters,andstorethembacktoRAMmemoryonlywhenleavingtheprocedure.Thisimprovestheexecutionspeedofcompiledprograms.-FrancescoBalena,Bari,ItalyVB51.evel:BeginningCENTERFORMSONSCREENApopularcodesnippetletsyou

14、centeranyformonthescreen,regardlessofthecurrentscreenresolution.YounowcanreachthesameresultbysimplyassigningthevalueVbStartUpScreen(=2)totheformsStartUpPositionnewproperty.YoucanevencenteraformwithinitsparentwindowbyassigningtheVbStartUpOwner(=1)value.YoucansetthispropertyfromthePropertywindow.Whena

15、formissupposedtobecenteredwithinitsparentwindow,remembertoaddasecondargumenttotheShowmethod:Form2.ShowVbModalzMe-FrancescoBalena,Bari,Italy0N-E16aDON,TAUTO-OPTIMIZEFORFASTCODEIfyoutakealookatVB,snativecodeoptimizationoptionsforthefirsttime,youmightbetemptedtoclick,onOptimizeforFastCoderightaway.Stra

16、ngeasitmaysound,though,thisdoesnotalwaysguaranteethebestperformance.Applicationsoptimizedforperformancegenerallydon,trunthatmuchfaster,butdohavealargermemoryfootprint.Thiscausesthemtoloadslower,especiallyonmemory-constrainedmachines,givingtheusertheimpressionthatyourappisactuallyslowerthanoneoptimiz

17、edforcompactcode.Forthesamereason,considerleavingyourapplicationscompiledasp-codeanyway.Especiallyforlarge,UI-anddatabase-intensiveapplications,theperformancegainofcompilingtonativecodewon,toutweightheincreaseinapplicationsize.Todetermineexactlywhichcompilationoptionisrightforyou,usetheVBApplication

18、PerformanceExplorer(APE)includedonyourVBCD.-MichieldeBruijn,Rotterdam,TheNetherlandsVBA51.evel:BeginningNOTA1.1.TEMP1.ATESARECREATEDEQUA1.UnliketemplatesinotherOffice97products,Word97templatesprovideabusiness-applicationenginethatremainsseparatefromthedocumentsthatusethatengine.TemplatebasedExcelwor

19、kbooksandPowerPointpresentationsincludeacopyofthatengine.Inpractice,allWorddocumentstwoVBAprojects:thefirstprojectisfromtheunderlyingtemplate),templateandthedocumentitself.On(allWorddocumentsarebasedonasecondprojectbelongstotheWordtheotherhand,ExcelworkbooksandPowerPointpresentationsbasedonatemplate

20、haveonlyoneVBAproject.Everyfilecontainsitsowncopyoftheprojectintheoriginaltemplate.Changesmadetothiscopydon,taffecttheunderlyingtemplate.InExcel,PowerPoint,andAccess,add-insprovidecodeenginesthatremainseparatefromtheworkbooksandpresentationsthatusethoseengines.TocreateanExcelorPowerPointadd-in,useth

21、eSaveAscommandontheFilemenuandsavethefileasaspecifictype:thenAdd-in11type.EachproductusesaspecificAdd-inextension(X1.AforExcel,PPAforPowerPoint,andMDAforAccess).There,snocanonicallocationforstoringadd-ins,buttoloadadd-insautomaticallywhenyoulaunchanOfficeproduct,storethemintheX1.StartfolderorintheSt

22、artUpfolder.Youcanloadadd-insmanuallywiththeAdd-inscommandontheToolsmenu,oryoucanautomatetheprocessincode.TocreateanAccessadd-in,usethecommandMakeMDEfileavailablethroughtheDatabaseUtilitiescommandontheToolsmenu.-ChristineSolomon,NewYork,NewYorkVB51.evel:BeginningCUSTOMIZEVBTOO1.BARSHereareafewsimple

23、waysyoucancustomizeyourVB5IDE:?AddtabstothecustomcontroltoolboxbyrightclickingontheGeneralbuttonandselectingtheAddTabcommand.Youcanalsomovetabsaroundanddeletethem,aswellasmovecontroliconsfromonetabtotheotherusingthedrag-and-dropmethod.?Createtoolbarbuttonsforanymenucommandbyrightclickingonanytoolbar

24、andselectingtheCustomizecommand.MovetotheCommandstab,selectthemenucommandintheright-mostlistbox,anddragitontothetoolbarwhereyouwanttomoveit.GoodcandidatesforthisprocedurearetheProject-References,Project-Properties,andTools-AddProcedurecommands.?CreateabrandnewtoolbarintheToolbarstaboftheCustomizedia

25、logbox.Afteryoudefineatoolbar,addbuttonsusingtheprocedureoutlinedabove.WhentheCustomizedialogboxisactive,right-clickonanytoolbarbuttontochangeitsimage,createagroupdivider,show/hidetext,andmore.-FrancescoBalena,Bari,ItalyHIDEA1.1.PROJECTWINDOWSWhenworkingwithmultipleprojects,itseasytogetconfusedbythe

26、manywindowsactiveonthescreenatthesametime.However,youcantemporarilyhideallthewindowsrelatedtoagivenprojectbysimplycollapsingtheprojectitemintheProjectExplorerwindow.YoucandisablethisfeatureintheGeneraltaboftheTools-Optionsdialogbox.-FrancescoBalena,Bari,ItalyVB51.evel:IntermediateFRIEND1.YENUMERATED

27、VA1.UESIfyoubuildanActiveXcontrolthatexposesanenumeratedproperty,youshoulddefineaPublicEnumstructurethatgathersallthepossiblevaluesforthatproperty.DoingthishelpsthedeveloperthatusesyourcontrolbecausetheenumeratedvalueswillbelistedinacomboboxinthePropertywindow.However,atfirstglance,itseemsimpossible

28、toachievethesamebehaviorasmostofVB,sintrinsiccontrols,whichexposeenumeratedpropertieswithshortdescriptionsandembeddedspaces.Evenifthey*renotdocumentedinthelanguagemanuals,youcancreateenumerateditemsthatembedspacesbysimplyenclosingtheirnameswithinsquarebrackets:PublicEnumDrawModeConstantsBlackness=1N

29、otMergePen)MaskNotPenNotCopyPenEndEnumThenaddaDrawModeConstantspropertycontrol.AlltheenumeratedvaluesappeartotheActiveXwindowoftheVBIDE,withoutthesquarebracketsallthespacesyouincluded.Usethistechniqueotherotherwiseforbiddencharacters,suchasinthePropertyandwithtoembedmathorpunctuationsymbols.-Frances

30、coBalena,Bari,ItalyVB416/32,VB51.evel:AdvancedIMP1.EMENTATIONOFPUB1.ICFORMANDC1.ASSVARIAB1.ESTheimplementationofPublicvariablesinformsandclasseschangedwithVisualBasic5.0.VB4implementspublicvariablesinformsandclassmodulesasifthey,reregularvariables,usingpointerstodatainmemory.InVB5zpublicvariablesare

31、morecorrectlyimplementedasapairofhiddenGet/1.etpropertyprocedures.ThisapproachslowsdownthesepropertieswhentheprogramisportedfromVB4toVB5.Moreimportantly,thischangelikelybreaksanycodethatreliesonpassingsuchvariablestoproceduresasByRefargumentsandexpectsthattheproceduremodifiesthem.Infact,underVB5zthe

32、yrepassedbyvalue,andtheoriginalpropertyisneveraffected.Formoreinformationonthisissue,seearticleQ166928intheMicrosoftKnowledgeBase.-FrancescoBalenazBari,ItalyVB416/32,VB5(EnterpriseEdition)1.evel:IntermediateSTANDA1.ONETYPE1.IBRARIESIfyoucreateout-of-processO1.Eservers,VisualBasicembedsthecompanionty

33、pelibraryintotheEXEfileandgeneratesnoT1.Bfile.However,ifyouowntheEnterpriseEditionofVB4orVB5,youcanflagtheRemoteServerFilecheckboxtohaveVisualBasiccreateastandalonetypelibrary.InVB5zyoucanfindthisoptionintheComponenttaboftheProject-Propertiesdialogbox.-FrancescoBalena,Bari,ItalyVB51.evel:Intermediat

34、eUSEOBJECTBROWSERTODISCOVERUNDOCUMENTEDFEATURESIfyouright-clickontheright-mostpaneoftheObjectBrowser,youcanissuetheShowHiddenMemberscommand.Fromthispointon,theObjectBrowsershowsallhiddenpropertiesandmethodsinanylibrary,andyoucanuseittoexploreallobjectlibrariesinmoredetail.Forinstance,theVBAlibraryex

35、posesahiddenclass,appropriatelynamed*_HiddenModule,whichincludesmanywell-knownVBAfunctionsplusthreeundocumentedones:ObjPtrzStrPtrzandVarPtr.ObjPtrreturnstheaddressoftheprivateareaofanobjectinstance,StrPtrreturnstheaddressofthefirstcharacterinastring,andVarPtrreturnstheaddressofavariableorastringdesc

36、riptor,ifyoupassitastringvariable.-FrancescoBalena,BarizItalyVB416/321.evel:AdvancedTHEADDRESSOFAVARIAB1.EVB5includesabuilt-inVarPtrfunction(seetipuUsetheObjectBrowsertoDiscoverUndocumentedFeatures*),butthisfunctionisn,tavailableinVB4.TheVB4runtimelibrarydoesincludethisfunction,butyoumustdeclareitfi

37、rst:#IfWinlThenDeclareFunctionVB40016.D1.1.As1.ong#ElseDeclareFunctionVB40032.D1.1.As1.ong#EndIfVarPtr1.ib_(variableAsAny)VarPtr1.ib_(variableAsAny)ThisfunctionisusefulwhenpassinganexternalAPIroutineaTypestructure,addressofanothervariableandoneofitsfieldsistheorrecord.-FrancescoBalenazBari,ItalyVB41

38、6/32,VB51.evel:IntermediateCROSSMIDNIGHTBENCHMARKSTraditionally,VBprogrammersbenchmarktheircodeusingtheTimerfunction.However,ifyourprocessmightterminateonthefollowingday,youmusttakeintoaccountthatthevaluereturnedbythatfunctionisresetatmidnight.Ifyou,resatisfiedwithone-secondprecision,youcansimplifyy

39、ourcodeusingtheNowfunction:DimStartTimeAsDateStartTime=Now,thecodetobebenchmarkedIPrintelapsedSeCondS=&Format5_(Now-StartTime)*86400z#)YouneedtheFormat$functiontoroundtheresulttothenearestInteger.-FrancescoBalena,Bari,ItalyVB51.evel:IntermediateAPP.PATHMIGHTRETURNUNCPATHSPECIFICATIONSUnlikeVB4,VB5,s

40、App.PathpropertymightreturnaUNCpath,suchas,serverrograms.)zundercertaincircumstances,dependingonhowtheprogramstartedandifitsinterpretedintheVBIDEorcompiledasastandaloneEXE.ThischangelikelyaffectsallapplicationsthatuseApp.Pathtosetthecurrentdirectorywhentheprogramstarts:ChDriveApp.PathChDirApp.PathIn

41、fact,becauseChDrivecannothandleUNCpaths,thecodemightraiseafatalruntimeerror,andshouldbeprotectedusinganOnErrorResumeNextstatement.Thisfixzhowever,doesntprotectyouundereverypossiblecondition.Thebestapproachistogivetheenduserthecapabilitytosettheapplicationdirectoryatruntime,thensavetheenteredvalueint

42、heregistryorinanINIfile.Formoreinformationonthisproblemanditspossiblesolutions,seearticleQ167167intheMicrosoftKnowledgeBase.-FrancescoBalena,Bari,ItalyVB416/32,VB51.evel:AdvancedMOREVERSATI1.EARRAYPARAMETERSYoucanwriteasingleprocedurethatacceptsanytypeofarrayasanargumentbyusingavariantparameter.With

43、intheprocedure,addressthearrayusingtheusualsyntax:,returnthenumberofitemsFunctionItemCount(anArrayAsVariant)As1.ongItemCount=UBound(anArray)-_1.Bound(anArray)+1,thefirstelementis,anArray(1.Bound(anArray)EndFunctionYoucanevenpassamatrixwithanynumberofdimensions;inordertounderstandhowmanydimensions,yo

44、umustiterateontheUBoundor1.Boundfunctionsuntilanerroroccurs:FunctionItemCount(anArrayAsVariant)As1.ongDimitemsAs1.ong,iAsIntegerOnErrorResumeNextitems=UBound(anArray)-1.Bound(anArray)+1Fori=2to999items=items*(UBound(anArray,i)-1.BoundfanArray,i)+1)IfErrThenExitForNextItemCount=itemsEndFunction-Franc

45、escoBalena,BarizItaly11-E1OAVB416/32,VB51.evel:IntermediateCOMPACTYOURCODEUSINGIIFANDSWITCHYoucanoftenreplaceanIf.Then.ElseblockwithamorecompactIIffunction:,returnsthemaxoftwovaluesmaxValue=IIf(first=second,first,second)Switchisararelyusedfunction,yetinmanycasesitprovesratherusefulasasubstituteforal

46、engthyIf.ElseIfblock:,is,x11negative,positiveornull?PrintSwitch(xO,positive*1,True,Null11)NotethelasttestisTrue,becausethethreeconditionsaremutuallyexclusiveandexhaustive.-FrancescoBalena,Bari,ItalyVB51.evel:AdvancedPROPERTIESTHATBEHAVE1.IKETEXTANDCAPTIONIfyoubuildanActiveXcontrolthatexposesaText-or

47、Caption-Iikeproperty,evenunderdifferentnames,youshouldmodifyitsattributesintheProcedureAttributedialogboxafterexpandingitusingtheAdvancedbutton.Thisway,theProcedureIDissettoTextorCaptionrespectively.ThiscausesyourpropertytobehavelikestandardTextorCaptionproperties.WhentheusermodifiesitsvalueinthePropertywindow,theeffectofeachnewcharacterisimmediatelyreflectedontheActiveXcontrolitself.-FrancescoBalena,Bari,ItalyVB51.evel:AdvancedCOMBINEDEFAU1.TWITHOTHERATTRIBUTESWhenbuildinganActiveXcontrol,youcansetadefaultpropertyormethodusingtheProcedureAttributesdialogbox,afterclickingontheAdvancedbutton

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 生活休闲 > 在线阅读


备案号:宁ICP备20000045号-2

经营许可证:宁B2-20210002

宁公网安备 64010402000987号