You are on page 1of 5

12/23/2015

ExcelVBAProgrammingOpeningTextandCSVfiles

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/open_a_text_file_in_vba.html

1/5

12/23/2015

ExcelVBAProgrammingOpeningTextandCSVfiles

OpenaTextFileinExcelVBA

BeingabletomanipulatetextandcsvfileswithExcelVBAisausefulprogrammingskilltoaddto
yourrepertoire.Inthissection,you'lllearnhowtodojustthat.

ACSVfile(CommaSeparatedValue)isonewheretheitemsoneachlineareseparatedby
commas,andthelineitselfendsinacarriagereturn(pressingtheEnterkeyonyourkeyboard).
Theylooklikethis:

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

2/5

12/23/2015

ExcelVBAProgrammingOpeningTextandCSVfiles

Ifyourfilehascommaseparatedvalues,youcansaveitwiththeendingin.csvor.txt.Files
endingincsvare,however,acommonformat,andwe'llstickwiththosetypesoffiles.
IfafilehaseachitemonalineseparatedwiththeTabcharacterthenitissaidtobeaTXTfile.
Theylooklikethis:

Youcan,ofcourse,openatextfilestraightfromExcel.JustusetheData>GetExternalData
fromTextoptionsontheExcelRibbon.ThiswouldthenbringuptheTextImportWizard.However,
asaVBAprogrammer,it'snicetoknowhowtodoityourself.Plus,youcandothingsby
manipulatingthetextfileyourselfthatyoucan'tdowiththeWizard.Whatwe'regoingtodoisto
openuptheaboveCSVfileandplacetheISBNintheAcolumn,ratherthaninthelastcolumnas
wehaveitatthemoment.
Tofollowalongwiththislesson,youcandownloadthefilebyclickingthelinkbelow.Rightclickthe
linkandsaveittoyourcomputer.Rememberthelocationwhereyousavethisfileto.
AuthorsCSVFile(Rightclicktosave)
InExcel,createanewblankworkbook.ClicktheAcolumnandformatitasText.Thisisbecause
ourISBNisinthenumberformatinthetextfile.IfyouleavetheAcolumnonGeneralthenyou'll
getastrangenumberfortheISBN.
NowopenupyourVBAEditortogetatthecodingwindow.CreateanewSubandcallit
OpenTextFile.Asthefirstlineofyourcode,addthefollowing:
DimFilePathAsString
ThisjustsetsupavariablecalledFilePath.
Wenowneedthelocationofourauthors.csvfile.WeplacedoursintheDocumentsfolder
(Windows7).Becauseit'sintheDocumentsfolder,wecanusethebuiltin
Application.DefaultFilePath.ThedefaultfilepathistheDocumentsfolder.Wethenonlyneedto
addonthefilename,precededbyabackslash:
FilePath=Application.DefaultFilePath&"\authors.csv"
Ifyouplacedyourfilesomewhereelse,youcandosomethinglikethisinstead:
FilePath="C:\Users\Owner\VBA\authors.csv"
ThisfilepathpointstoafoldercalledVBAthatisintheOwnerfolderinC:\Users.Butamendyour
ownfilepathtopointtowhereyousavedyourauthors.csvfile.
Toopenafile,youstartwiththewordOpen.YouthenspecifyaFileName,aMode,andaFile
Number.
OpenFileNameForModeAsFileNumber
TheModeaboveshouldbereplacedbyoneofthefollowing:
Appendusedforaddingdatatoanalreadyexistingfile
Outputusedtowritetoafile
Inputusedtoreadafile
Binaryusedtoreadorwritedatainbyteformat
Randomusedtoplacecharactersinabufferofasetsize
TheModesthatwe'reinterestedinaretheInputandOutputones.
TheFileNumbercanbeanynumberbetween1and511.Youprecedethenumberwiththe#
character.Soifyou'reopeningonefileyou'dhave#1.Ifyouopenupasecond,differentfileit
http://www.homeandlearn.org/open_a_text_file_in_vba.html

3/5

12/23/2015

ExcelVBAProgrammingOpeningTextandCSVfiles

wouldbe#2,andsoon.
Soaddthislinetoyourcode:
OpenFilePathForInputAs#1
ThefilewewanttoopenistheonewestoredinthevariablecalledFilePath.Youcanalsotype
theentirefilepathhere,enclosedindoublequotes:
Open"C:\Users\Owner\VBA\authors.csv"ForInputAs#1
Wewanttoreadthisfileonly,sowehaveForInput.Thisisthefirstfilewe'regoingtoopen,soit
is#1(filenumber1).
Thenextlineistosetavariableforrownumbers.We'llusethisfortheActiveCellonthe
spreadsheet:
row_number=0
Atthemoment,we'veonlytoldVBAtoopenthefile.Wehaven'tactuallydoneanythingwithit.The
wayyounormallydosomethingwithafileistoloopround,grabbingeachlineasyougo.We'lluse
aDoUntilloopforthis:
DoUntilEOF(1)
Loop
Noticethestrangeendcondition:EOF(1).TheEOFmeansEndOfFile,whilethe1inround
bracketsisthefilenumberyouspecifiedearlier.
Insideoftheloop,wefirsthavethissomewhatcomplexline:
LineInput#1,LineFromFile
Thefirstthreeitemsbeforethecommarefertoasinglelineofinputfromyourfilenumber(#1).
Afterthecomma,youtellVBAwhereyouwanttoplacethisline.Thiswillbeavariable.We've
calledoursLineFromFile.Everytimeroundtheloop,anewlinewillbegrabbedfromthetextfile
andplacedinthisvariable.
Nowthatyouhavealinefromyourtextfile,youneedtodosomethingwithit.However,thelinewill
stillhaveallthecommasinit.Sothefirstlineforuswillbethis:
Christopher,Brookmyre,9780349114903
Youneedtoparsethelinesfromyourtextfileinsomeway.Agoodwaytoparsealineiswiththe
Splitfunctionyoumetearlier.ByusingSplit,youcanplaceeachitemfromalineintoanarray:
LineItems=Split(LineFromFile,",")
BetweentheroundbracketsofSplit,wehavethevariablewewanttosplit,whichis
LineFromFile.Afteracomma,wehavetheseparatorwewanttolookfor.Theseparatoristhe
comma,forus.
WhenSplithasfinished,we'llhaveanarraycalledLineItems.Ourtextfilealwayshasthreeitems
perline(firstname,lastname,ISBN).Soweknowthearraygoesfrom0to2positions.Wecan
nowgoaheadandplaceeachitemintoacellonthespreadsheet:
ActiveCell.Offset(row_number,0).Value=LineItems(2)
ActiveCell.Offset(row_number,1).Value=LineItems(1)
ActiveCell.Offset(row_number,2).Value=LineItems(0)
BetweentheroundbracketsofOffsetwehavetherownumberandthecolumnnumber.We're
usingthevariablecalledrow_numberfortherows.Wesetthisto0earlier.(We'llincrementthis
variableshortly).Thecolumnsarealwaysoffsetat0,1and2.Avalueof0,remember,keepsyou
inthesamecolumn.Avalueof1movesyou1columnover,andavalueof2movesyou2
columnsoverfromtheActiveCell.
Totherightoftheequalsign,wehaveourLineItemsarray.BecausewewanttheISBNintheA
column,we'veusedLineItems(2)asthefirstvalueaftertheequalsign.Wenexthave
LineItems(1),whichwillgetusthelastnameintheBcolumn.Finally,wehaveLineItems(0),
whichwillgetusthefirstnameintheCcolumn.
http://www.homeandlearn.org/open_a_text_file_in_vba.html

4/5

12/23/2015

ExcelVBAProgrammingOpeningTextandCSVfiles

Thefinalthingtodoinsideoftheloopistoincrementtherow_numbervariable,otherwisewe'llbe
stuckonthefirstrowofthespreadsheet.
row_number=row_number+1
Whenyouopenafile,youshouldcloseitsomewhereinyourcode.Thisisfairlystraightforward:
Close#1
YoutypethewordCloseandthen,afteraspace,thefilenumberyou'retryingtoclose.
Butthewholeofyourcodeshouldlooklikethis:

Testitout.MakesureanycellintheAcolumnistheActivecellonyourspreadsheet(theAcolumn
istheoneyourformattedtoText).Gobacktoyourcode.Clickanywhereinsideofyoursuband
pressF5torunit.Gobacktoyourspreadsheetandyoushouldfindthatthedatafromthetextfile
hasbeenimported:

Andtherewego!We'veopenedupaCSVfile,reorderedthecolumnsandplacedtheinformation
intocellsonaspreadsheet.We'llnowlookatwritingtoatextfile.

WritetoaTextFilewithExcelVBA>
LotsmorefreeonlinecoursehereonourmainHomeandLearnsite
AllcoursematerialcopyrightKenCarney

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

5/5

You might also like