Anda di halaman 1dari 6

12/23/2015

ExcelVBAProgrammingWriteToATextFile

ExcelVBAProgramming
Home
GettingStarted
8partsection>>
VBAProgrammingVariables
6PartSection>>
ConditionalLogic
9partsection>>
StringsandStringFunctions
8PartSection
ProgrammingLoops
4PartSection
ProgrammingArrays
4PartSection
SubsandFunctions
6PartSection
ExcelVBAandTextFiles
OpenaTextFile
Writingtoatextfile
ExcelVBAandUserForms
5partsection>>
AnExcelPictureViewerProject
12partsection>>
ExcelVBAandCharts
4partsection>>
ATreeViewProject
A4partsection>>
>BUYTHEBOOKOFTHISCOURSE<

http://www.homeandlearn.org/write_to_a_text_file.html

1/6

12/23/2015

ExcelVBAProgrammingWriteToATextFile

WritingtotextfilesinExcelVBA

Inthepreviouslesson,yousawhowtoopenupatextfilewithExcelVBAcode.Inthislesson,
you'lllearnhowtowritedatafromaspreadsheettoatextfile.Whatwe'lldoistakeourreordered
columnsfromlasttimeandwritethembacktoaCSVfile.
Thefirstjobistofindawaytoreferencethecellsonthespreadsheetthatwewant.Wecanthen
looproundallthesecellsgettingthevalues.
Ourspreadsheetis3columnswideby8rowshigh:

Wecouldhavetwoloopstocyclethroughthedataabove,aninnerloopandouterone.Likethis:
http://www.homeandlearn.org/write_to_a_text_file.html

2/6

12/23/2015

ExcelVBAProgrammingWriteToATextFile

Fori=1To8
Forj=1To3
Nextj
Nexti
Theouterloopgoesfrom1to8.Thisisthenumberofrowswehave.Theinnerloopgoesfrom1
to3,whichisthenumbercolumns.
However,supposewedecidedtoaddmorerows,ormorecolumnstothespreadsheet.Itwould
meanourloopwouldnotpickupthenewdata.Abetterwayistogetthelastrowwithdatainitand
thelastcolumnwithdata.Wecouldthenhavethisfortheloops:
Fori=1ToLastRow
Forj=1ToLastColumn
Nextj
Nexti
Thequestionis,howdowegetthesevalues?
Therearelotsofwaytogetthelastrowandlastcolumnwithdata.Apopularwaytogetthelast
rowwithdatain,forexample,isthis:
LastRow=Cells(1,"A").End(xlDown).Row
ThiscodefirstgoestotheverylastrowinExcel,nomatterwhichversionyouhave(olderversions
ofExcelhavefewerrowsthanlaterversions).ItthengoesbackuptofindthelastcellincolumnA
thathassomethinginit.Asimilartechniqueisusedtofindthelastcolumnwithdata.
Thetechniqueweprefer,though,isthis:
LastRow=ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row
Thisreferstoanyrangeinyouractiveworksheetwithdatainit.TheinbuiltSpecialCellsisthen
used.InbetweentheroundbracketsofspecialSpecialCellsistheconstantxlCellTypeLastCell.
Thisgetsyouthelastcellwithdata.Afteradot,youcantypeeitherRoworColumn,depending
onwhichlastcellyouwant.
We'realmostreadytostartwritingthecode.Toactuallyopenatextfileforwriting,though,you
needthis:
OpenFilePathForOutputAs#1
Thisisthesameasbefore,exceptfortheuseofthekeywordOutput.VBAwillthentrytoopenup
yourfile.IfafileoftheonenamedinFilePathdoesn'texistitwillbecreatedforyou.Ifthefiledoes
existthenitwillbeoverwritten.(Ifyouwantthenewcontentstobeaddedtotheendofyourfile
thenyouwoulduseAppendinsteadofOutput.)
Todotheactualwritingtothefileyouneedthis:
Write#1,File_Contents
AfterthewordWriteyoutypeyourfilenumber.Afteracomma,youneedthecontentsyouwishto
writetothefile.
Withthatinmind,let'swritesomecode.
CreateanewSubandcallitWriteTextFile.AddthefollowingfourvariablestoyournewSub:
DimFilePathAsString
DimCellDataAsString
DimLastColAsLong
DimLastRowAsLong
Togetthelastrowandcolumnwithdata,addthefollowingtwolines:
LastCol=ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Column
http://www.homeandlearn.org/write_to_a_text_file.html

3/6

12/23/2015

ExcelVBAProgrammingWriteToATextFile

LastRow=ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row
Youthenneedafilepath,asbefore:
FilePath=Application.DefaultFilePath&"\auth.csv"
Thispointstoafilecalledauth.csvintheDocumentsfolder.IfthereisnosuchfilethenVBAwill
createoneforus.
ThenextlinetoaddistheonethatopensthefileforOutput:
OpenFilePathForOutputAs#2
Noticethatthefilenumberattheend,#2.We'vealreadyused#1previously,sowe'lltry#2to
avoidanyconflicts.(NOTE:Onsomesystems,youmaygetanerrortellingyouthefileisalready
openwhenyourunthecode.Ifso,closedownExcelandreopenit.)
ThenextcodetoaddisthedoubleForLoop.Thisisquitecomplexsodon'tworryifyoudon't
understanditatfirst.Keepstudyingitanditwillmakesense.Hereitis:
Fori=1ToLastRow
Forj=1ToLastCol
Ifj=LastColThen
CellData=CellData+Trim(ActiveCell(i,j).Value)
Else
CellData=CellData+Trim(ActiveCell(i,j).Value)+","
EndIf
Nextj
Write#2,CellData
CellData=""
Nexti
Aswesaid,we'reloopingroundcellsonthespreadsheet.Theouterlooptakescareoftherows
andtheinnerlooptakescareofthecolumn.
Insidetheinnerloop,wehavethisIfStatement:
Ifj=LastColThen
CellData=CellData+Trim(ActiveCell(i,j).Value)
Else
CellData=CellData+Trim(ActiveCell(i,j).Value)+","
EndIf
Thereasonwhywewanttoknowifj=LastColisbecauseofthecommas.Wewanteachlinein
ourtextfiletolooklikethis,remember:
9780349114903,Brookmyre,Christopher
We'regettingonecellatatimefromthespreadsheet.Eachoftheitemsneedstobeseparatedby
acomma.However,there'snocommaattheend,whichisthethirditem.IfjdoesequalLastCol
thenthisgetsexecuted:
CellData=CellData+Trim(ActiveCell(i,j).Value)
WhateverisintheActiveCelli,jwillhaveitsValueplacedintothevariablecalledCellData.
However,ifjdoesnotequalLastRowthenthisgetsexecutedinstead:
CellData=CellData+Trim(ActiveCell(i,j).Value)+","
http://www.homeandlearn.org/write_to_a_text_file.html

4/6

12/23/2015

ExcelVBAProgrammingWriteToATextFile

Theonlydifferenceisthecommaontheend.Thefirsttimeroundtheinnerloop,CellDatawillhold
thisvalue:
9780349114903,
Thenexttimerounditwillholdthis:
9780349114903,Brookmyre,
Andthefinaltimerounditwillholdthisvalue:
9780349114903,Brookmyre,Christopher
Outsideoftheinnerloop,butjustbeforetheNextioftheouterloop,wehavethesetwolines:
Write#2,CellData
CellData=""
Thefirstlineistheonethatactuallywritesthenewlinetothetextfile.Thesecondlineresetsthe
CellDatavariabletoablankstring.
Thefinaltwolinesofcodearethese,bothoutsideofthetwoloops,attheend:
Close#2
MsgBox("Done")
Theselinesclosethefileandthendisplayamessagebox.
Thewholeofthecodelookslikethis:

Runyourcodeandtryitout.Nowlocateyournewtextfile.Youshouldfindthatitlookslikethis:
(Don'tworryaboutthedoublequotesthatVBAhasaddedtothebeginningandendofeachline.)

http://www.homeandlearn.org/write_to_a_text_file.html

5/6

12/23/2015

ExcelVBAProgrammingWriteToATextFile

Inthenextsection,you'llmakeastartlearningaboutUserForms.

ExcelVBAUserForms>
LotsmorefreeonlinecoursehereonourmainHomeandLearnsite
AllcoursematerialcopyrightKenCarney

http://www.homeandlearn.org/write_to_a_text_file.html

6/6

Anda mungkin juga menyukai