Tải bản đầy đủ - 0 (trang)
Chapter 8. Opening, Saving, and Sharing Workbooks

Chapter 8. Opening, Saving, and Sharing Workbooks

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

Respondtoeventsthatoccurwithinaworkbook

Thischapterincludestask-orientedreferenceinformationfor

thefollowingobjectsandtheirrelatedcollections:Workbookand

RecentFile.



Codeusedinthischapterandadditionalsamplesareavailablein

ch08.xls.







8.1.Add,Open,Save,andClose

UseWorkbookobjectstoopen,save,andcontrolfilesinExcel.To

createanew,emptyfileinExcel,usetheAddmethodonthe

Workbookscollection:

DimwbAsWorkbook

Setwb=Application.Workbooks.Add



UsetheWorkbookobject'sSaveorSaveAsmethodtonamethe

workbookandsavethefiletodisk.Thedefaultsavelocationin

ExcelissetintheApplicationobject'sDefaultFilePathproperty,

whichisusuallyMyDocuments.Forexample,thefollowingline

savestheworkbookcreatedbeforeasNewWorkbook.xlsinMy

Documents:

wb.SaveAs"NewWorkbook"



TheSavemethodissimilartoSaveAs,exceptitusesthedefault

filename(Bookn.xls)thefirsttimeafileissaved.UseSaveAsthe

firsttimeyousaveafileortosaveanexistingworkbookina

newfile;useSavewhenyouwanttokeeptheworkbook's

currentname.

UsetheClosemethodtocloseanopenworkbook.Closingdoes

notautomaticallysavechangestotheworkbook,butifthere

areanychanges,ExceldisplaysaSaveChangesdialogbox

beforeclosing.Youmustcloseaworkbookbeforeitcanbe

deleted.Exceldoesn'tprovideobjectstodeleteworkbookssince

theyaresimplyfilesstoredondisk.Instead,youusetheKill

methodorasimilartechniquetodeleteaworkbook.The

followingcodeclosestheworkbookcreatedpreviouslyand



deletesit:

wb.Close

VBA.Kill"NewWorkbook.xls"



Ifyouwanttoopenanexistingworkbook,usetheOpenmethod:

Setwb=Application.Workbooks.Open("MyBook.xls")



AswithSave,Excellooksfirstinthecurrentdefaultdirectory,

whichmayormaynotbewheretheworkbookislocated.Inthis

book,IoftenusetheWorkbook'sPathpropertytotellExceltolook

inthesamefolderthatthecurrentworkbookresidesin:



Setwb=Application.Workbooks.Open(ThisWorkbook.Path&"\MyBoo



ThisworkswellformebecauseI'vestructuredmysamplesso

thatrelatedonesareallinthesamefolder.Also,Idon'tknow

wherethatfoldermightbeinstalledonyourmachineIjust

assumethey'llbekepttogetherinthesamefolder.



8.1.1.Templates

ThewayExcelcomesfromMicrosoft,newworkbookscontain

threeworksheetsandnochartsorothersheets.Youcan

changethisbysettingExcel'sOptions(Tools Options

Generaltab),butsometimesyoujustwanttocreatea

workbookwithoneworksheetincode,leavingtheOption

settingsalone.There'saneasywaytodothis:



Setwb=Workbooks.Add(XlWBATemplate.xlWBATWorksheet)



Theprecedinglinecreatesanewworkbookcontainingone

worksheet.Youcanuseasimilarlinetocreateaworkbook

containingonechart:

Setwb=Workbooks.Add(XlWBATemplate.xlWBATChart)



Ofcourse,youcanalsousetheAddmethodtocreateanew

workbookbasedonatemplate,asshownhere:

Setwb=Workbooks.Add("C:\ProgramFiles\Microsoft

Office\Templates\1033\timecard.xlt")



8.1.2.OpenasRead-OnlyorwithPasswords

TheOpenmethodisactuallyquitecomplex.Ifyoutype

Workbooks.OpenintheCodewindow,VisualBasicdisplaysa

dizzyingarrayofpossiblearguments(Figure8-1).



Figure8-1.TheOpenmethodcanbecomplex



Thankfully,onlyFilenameisrequired!Mostofthesearepretty

special-purpose(youcanreadaboutthemlater);themost

importantonesareReadOnly,Password,andFormat.Openingafile

asread-onlyishandyifaworkbookisstoredatanetwork

locationandmightbeopenbyanotheruserinthatcaseyoucan

openthefileonlyasread-only:



Setwb=Workbooks.Open("//wombat1/public/copyoffiles.xls",,



Ifyoutrytoopenaworkbookthathasapasswordincode,

Excelwillprompttheuserforthatpassword.Youcanavoidthis

byputtingthepasswordincode:



Setwb=Workbooks.Open(ThisWorkbook.Path&"/security.xls",,



Ofcourse,that'saspectacularlybadideaifyouareatall

concernedaboutsecurity:neverwritepasswords,usernames,

emailaddresses,orothersensitivedataincode.Theonly

reasontousethisapproachisifyourpasswordsaremerely

intendedtopreventaccidentalaccesstheanalogywouldbe

closingyourfrontdoorratherthanlockingit,lockingitand

settingthealarm,orlockingit,settingthealarm,andreleasing

raveninghounds;yougettheidea.

Finally,theFormatargumentletsyouopentextfilesasExcel

workbooks.IfFormatis1,Excelinterpretstabcharactersinthe

fileasnewcolumns.Eachlineinthefileisanewrow.For

example,atextfilethatlookslikeFigure8-2canbeopenedas

aworkbookusingthiscode:



Setwb=Workbooks.Open(ThisWorkbook.Path&"/data.txt",,,1)



resultinginaworkbookthatlookslikeFigure8-3.



Figure8-2.Atabbedtextfile



Figure8-3.ThetabbedfileopeninExcel



Thatsaid,theFormatargumentisabitobsolete.Instead,you

canusetheOpenTextmethodtodothesametaskandhavemuch

morecontroloverhowthetextfileisinterpreted.Thenext

sectiondiscussesthattechnique.



8.1.3.OpenTextFiles

ReadingdatafromtextfilesintoExcelisprobablythemost

commonprogrammingtaskinExcel.No,it'snotexciting(atall)

butthereisasurprisingamountofdatacomingfromtextfiles

intoExcel.Tab-delimitedandcomma-delimitedtextfilesarea

sortofuniversaldataformatmostsystemscanreadandwrite

thoseformats.Excelisverygoodatit.



Firstsomebasics.Therearetwosortsoftextdatafiles:

delimitedfiles(justmentioned)andfixed-widthfiles.Delimited

filesusecommas,tabs,semicolons,orsomeothercharacterto

separatefieldsofdata.Infixed-widthfiles,eachfieldbeginsat

afixedlocation.Ifdatainafielddoesn'tfillthatfield,therest

ofthefieldcontainsspaces.

Eachlineinadatafilerepresentsarecord.Lineisanimprecise

term,however.Differentsystemshavedifferentstandardsfor

whatisconsideredaline.OnWindowssystems,anewlineis

indicatedbythecarriage-returnandline-feedcharacters

(Chr(13)andChr(10)orvbCrLfinVisualBasic).OnMacintoshand

Linuxsystems,it'sjustlinefeed(Chr(10)).

WhenExcelopensatextfile,itneedstoknowhowthefields

andrecordsareidentified.Onceithasthatinformation,itcan

readthetextfile,placefieldsintocolumns,andcreateanew

rowforeachrecord.Excelcanguessatalotofthatforexample,

itjustassumesthatthefilewascreatedbytheoperating

systemthatExceliscurrentlyrunningunderandyoucansee

theseassumptionsbychoosingFile Open txtfiletorun

theExcelTextImportWizard(Figure8-4).

YoucanchooseTools Macro RecordMacrobeforerunning

theTextImportWizardtogeneratethecodeneededtoimporta

particulartextfile.Forexample,thefollowingcodewas

recordedwhenIimportedmysampletextfileinExcel:



'Recordedcode.

SubMacro1()

Workbooks.OpenTextFilename:=_

"C:\DocumentsandSettings\Jeff\MyDocuments\ProgrammingEx

,Origin:=xlWindows,StartRow:=1,DataType:=xlDelimited,Te

:=xlDoubleQuote,ConsecutiveDelimiter:=False,Tab:=False,S

False,Comma:=True,Space:=False,Other:=False,FieldInfo:=

1,9),Array(2,1),Array(3,9),Array(4,9),Array(5,1),

Array(6,1),Array(7,1),Array(8,9),Array(9,9),Array(1

TrailingMinusNumbers:=True



EndSub



Figure8-4.Excel'sTextImportWizard



ThekeypartsofthiscodearetheFilename,StartRow,DataType,

Comma(delimiter),andFieldInfo.Ifyouaregoingtoreusethis

code,itmakessensetoreorganizeitabit,asshownhere:



'Modificationstorecordedcode.

SubTestOpenTextModifiedCode()

Dimfld,filAsString

'Filenametoopen(lookinthisworkbook'sfolder)

fil=ThisWorkbook.Path&"\products.txt"

'Arraydescribinghowtoformatoromitcolumns.

fld=Array(Array(1,xlSkipColumn),Array(2,xlGeneralFormat)

Array(3,xlSkipColumn),Array(4,xlSkipColumn),_



Array(5,xlGeneralFormat),Array(6,xlGeneralFormat),_

Array(7,xlGeneralFormat),Array(8,xlSkipColumn),_

Array(9,xlSkipColumn),Array(10,xlSkipColumn))

'Createaworkbookandloadthetextfile.

Workbooks.OpenTextfil,,1,xlDelimited,,,,,True,,,,

EndSub



Thechangestotherecordedcodearespelledouthere:

1. Replacedtheabsolutepath-andfilenameswithavariable

usingthecurrentworkbook'spath.Thismakesiteasierto

adaptthecodeforotherfilesinthefuture.

2. RewrotetheFieldInfoarraystousetheExcelconstants.The

firstelementofeacharrayisthecolumnnumber;the

secondelementdescribeswhetherornottoincludethe

columnandtheformatforthecolumn.Inthiscase,1=

xlGeneralFormatand9=xlSkipColumn.Usingtheconstants

makesiteasiertounderstandwhatisgoingon.Table8-1

liststheseconstantsforyourreference.

3. RemovedthedefaultargumentsfromtheOpenTextmethod.

ItemsthatIdidn'tchangeintheTextImportWizardcan

simplybeomitted.Incode,thismakestheimportantitems

standoutmore.Ialsoremovedtheargument

namesMicrosofteliminatedtheconceptofnamedarguments

in.NETandIthinkthatindicatestheyaren'treallyvery

helpful.

Someofthesechangesareamatterofpreferenceforinstance,

youmaylikenamedargumentsandwanttokeepthem.My

pointhereistoshowyouhowtheTextImportWizardcanhelp

youtacklethemultifacetedOpenTextmethod.

Table8-1.FieldInfoxlColumnDataTypeconstantsandvalues



Constant



Value



Constant



Value



xlGeneralFormat



1



xlMYDFormat



6



xlTextFormat



2



xlDYMFormat



7



xlMDYFormat



3



xlYDMFormat



8



xlDMYFormat



4



xlSkipColumn



9



xlYMDFormat



5



xlEMDFormat



10



8.1.4.OpenXMLFiles

ImportantXMLfeaturesarepartofExcel2003Professionaland

standaloneversionsforWindows.EarlierandMacintoshversionsof

ExcelsupportonlylimitedaccesstoXMLfiles.



Textfilesmaybetheuniversaldataformatoftoday,butthe

futurebelongstoXML.XMLisactuallyatypeoftextfile,since

XMLfilesarestoredastext.Butunlikedelimitedtextfiles,they

areself-describing.ThatmeansExceldoesn'thavetoguess

whereafieldorrecordstarts;theinformationisrighttherein

thefile:





2002







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

Chapter 8. Opening, Saving, and Sharing Workbooks

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

×