Tải bản đầy đủ - 0 (trang)
Chapter 25. Programming Excel with .NET

Chapter 25. Programming Excel with .NET

Tải bản đầy đủ - 0trang

Codeusedinthischapterandadditionalsamplesareavailablein

ch25.xls.



25.1.ApproachestoWorkingwith.NET

Therearethreemainapproachestousing.NETwithExcel.You

canuse.NETtocreate:



ComponentsthatcanbeusedfromExcelmacros

ThisapproachworkswithallExcelversionsandismuchthe

sameascreatingCOMcomponentsforusewithExcelusing

earlierversionsofVisualBasic.The.NETtoolsautomatically

generatethetypelibrariesneededtouse.NETobjectsfrom

COMapplicationssuchasExcel.



StandaloneapplicationsthatuseExcelasacomponent

ThisapproachworksbestwithExcelXPand2003,since

thoseversionsprovidethefilesneededtouseExcelfrom

.NETapplicationssmoothly.Inthisscenario,theuserstarts

astandaloneapplicationtocreateormodifyExcelwo

rkbooks.



Workbook-basedapplicationsthatrunalloftheircodeas.NET

ThisapproachworksforExcel2003andlater.Inthis

scenario,theuseropenstheworkbook,whichautomatically

loadsthe.NETassemblycontainingtheapplicationcode.

Theworkbookcontainsalinktothisassembly,sothe

workbookfile(.xls)canbedistributedtomanydifferent

usersandlocations,whiletheassembly(.dll)residesina

singlelocation(forexampleatanetworkaddress).



Fromtheuser'sstandpoint,themaindifferencesbetweenthese

approachesarehowyoustarttheapplicationandwhatversions

ofExcelaresupported.Fromadeveloper'sstandpoint,the

differencesaffecthowyoudevelop,debug,anddeploythe

applications.Eventhedevelopmenttoolsyouneedvary

somewhatbetweentheseapproachesasdescribedinTable251.

Table25-1.SoftwarerequirementsfordevelopingbetweenExceland

.NET

Tocreate



Youneed



.NETcomponentsfor

useinExcel



VisualStudio.NETStandardEditionorhigher



Standalone.NET

applicationsthatuse

Excel



VisualStudio.NETStandardEditionorhigher,MicrosoftOffice

2002orlater,andPrimaryInteropAssemblies(PIAs)



Excel.NETapplications



VisualStudio.NETToolsforOffice(includesprojecttemplates)

andMicrosoftOffice2003orlater







25.2.Create.NETComponentsforExcel

IfyouareanexperiencedVBAprogrammer,thisisagreatway

tostartlearning.NETbecauseyoucantakeadvantageof

featuresbuiltintothe.NETFrameworkinsmall,incremental

steps.

Tocreatea.NETcomponentforuseinExcel:

1. FromwithinVisualStudio.NET,createanewclasslibrary

projectusingVisualBasic.NETorC#.VisualStudiocreates

afolderandtemplatefilesfortheproject,asshownin

Figure25-1.



Figure25-1.Anew,empty.NETclasslibrary

project



2. FromtheProjectmenu,chooseAddClass.VisualStudio

displaystheAddNewItemdialogboxshowninFigure25-2.



3. GivethenewclassadescriptivenameandclickOK.Visual

StudioregisterstheprojecttointeroperatewithCOM(the

RegisterforCOMInteropselectionontheProjectOptions,

Builddialogbox)andcreatesanew,emptycodetemplate

foryourclassasshowninFigure25-3.

4. Addcodetotheclasslibraryfortheobjects,properties,and

methodsyouwanttousefromExcel.

5. CompiletheprojectbyselectingBuildSolutionfromthe

Buildmenu.VisualStudiobuildstheclasslibraryasa.NET

assembly(.dll)andcreatesatypelibraryfile(.tlb)that

allowsExcelandotherCOMapplicationstousethat

assembly.Bothofthesefilesareplacedina\binfolder

withintheprojectfoldercreatedinStep1.

Forexample,theNetForExcelproject(NetForExcel.sln)includes

asimpleclassthatprovidesasinglemethodthatdisplaysa

messagepassedinasanargument:

'.NETcode.

PublicClassNetObject

PublicSubTest(ByValargAsString)

MsgBox(arg)

EndSub

EndClass



Figure25-2.CreateanewCOMclasstocontain

componentsforusefromExcel



Figure25-3.TheCOMclasscodetemplate

containsthebasicelementsyouneedfora

component



Thefollowingsectionshowsyouhowtousethissample.NET

componentfromwithinExcel.



25.3.Use.NETComponentsinExcel

Onceyoucompilea.NETcomponentwithRegisterforCOM

Interopenabled,usingthatcomponentfromExcelissimplya

matteroffollowingthesesteps:

1. FromwithintheExcelVBAEditor,selectReferencesfrom

theToolsmenu.VBAdisplaystheReferencesdialogbox.

2. ClickBrowseandnavigatetothe\binfolderforthe.NET

componentyouwishtouse.Selectthetypelibrary(.tlb)for

thecomponent,asshowninFigure25-4,andclickOKto

addareferencetothatcomponent.



Figure25-4.Usethe.NETcomponent'stype

librarytocreateareferencetothecomponentin

ExcelVBA



3. ClickOKtoclosetheReferencesdialogbox.



4. Declareanobjectvariableforthe.NETclassusingtheNew

keyword,thencallthemembersoftheclass.

ThecomponentsyoucreateusingVisualBasic.NETarenamed

usingtheirprojectname(.NETcallsthatthenamespaceofthe

component),soyouwouldusethefollowingcodetocallthe

NetForExcelproject'sNetObjectcreatedintheprecedingsection:

'Excelcode

SubTestNetObj()

DimxAsNewNetForExcel.NetObject

x.Test"Iworked!"

EndSub



Now,ifyouruntheprecedingcode,Excelusesthetypelibrary

tostartthe.NETassemblyandinvoketheTestmethodwitha

stringargument.The.NETcomponent,inturn,displaysa

messageboxsaying"Iworked!"

Thoughthatdemonstrationisn'tveryimpressive,whatyoucan

dowith.NETcomponentsbecomesexcitingonceyou'velearned

moreabouttheclassesthatcomewiththe.NETFramework.For

example,youcandosomeprettyusefulthingswitheventhe

basic.NETStringandArrayclasses,asshownhere:

'.NETcode

PublicClassNetString



+COMGUIDS



'AcreatableCOMclassmusthaveaPublicSubNew()

'withnoparameters;otherwise,theclasswillnotbe

'registeredintheCOMregistryandcannotbecreated

'viaCreateObject.

PublicSubNew()

MyBase.New()



EndSub



PublicFunctionSplit(ByValargAsString,_

OptionalByValsepAsString="")AsString()

IfLen(sep)<>1Then_

ThrowNewException("Separatormustbeonecharacter

Returnarg.Split(CType(sep,Char))

EndFunction



PublicFunctionJoin(ByValarg()AsString,_

OptionalByValsepAsString="")AsString

IfIsArray(arg)Then

Ifarg.Rank<>1Then_

ThrowNewException("Arraymusthaveonedimensio

Else

ThrowNewException("Firstargumentmustbeanarra

EndIf

ReturnString.Join(sep,arg)

EndFunction



PublicFunctionSort(ByValargAsString,_

OptionalByValascendingAsBoolean=True)AsString

'Declareanarray.

Dimar()AsString

'Breakthestringupandputitinthearray.

ar=arg.Split(""c)

'Sortthearray.

'ar.Sort(ar)

Reversetheorderifrequested.

IfNotascendingThenar.Reverse(ar)

'Convertthearraybacktoastringandreturnit.

ReturnString.Join("",ar)

EndFunction

EndClass



Tousethepreceding.NETclassincode,compiletheproject

andestablishareferencetothatprojectinExcel'sVBAEditor,

thenwritecodesimilartothefollowing:

'Excelcode

SubTestNetString()

DimstrAsString,ar()AsString,iAsInteger

DimNetStrAsNewNetForExcel.NetString

str="Somerandomtextthatyou'dwanttosort."

Debug.PrintNetStr.Sort(str)

ar=NetStr.Split(str)

Fori=0ToUBound(ar)

Debug.Printar(i)

Next

EndSub



TheprecedingcodedisplaysthesortedstringintheImmediate

window,thensplitsthestringintoanarrayanddisplaysitone

wordatatime.SinceVisualStudio.NETgeneratesatype

libraryforthecomponentandregistersitwithyoursystem,you

automaticallygetIntellisenseandAutoCompletefeatureswhen

youworkwith.NETobjectsinExcelVBA,asshowninFigure

25-5.



Figure25-5..NETobjectsregisteredforCOM

automaticallygetIntellisenseandAutoComplete

inVBA



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 25. Programming Excel with .NET

Tải bản đầy đủ ngay(0 tr)

×
x