资源描述:
《vba 读写文件(vba read and write files)》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、vba读写文件(VBAreadandwritefiles)VBAreadandwritefiles.TxtProcessingtextfiles1,OpenstatementSyntax:Open,pathname,For,mode,[Access,access],[lock],,As,[#]filenumber,[Len=reclength]Amongthem,access,lock,reclengthareoptionalparameters,generallydonotuse.Modespecifiesthewaytoopenafile.Thereare5kinds:Input:ope
2、nasinput,iereadmode.Output:openinoutputmode,thatis,writemode.Append:openbyappending,thatis,addingcontenttotheendofthefile.Binary:Opensinbinarymode.Random:openinarandomway,andifnotspecified,openthefileinRandommode.Filenumberisavalidfilenumberrangingfrom1to511.YoucanspecifyorusetheFreeFilefunctiontog
3、etthenextavailablefilenumber.Explanation:ifthefilespecifiedbypathnamedoesnotexist,youcanbuildthisfilewhenyouopenthefileinAppend,Binary,Output,orRandommode.Example:Open"F:TEST.txt"ForInputAs#1isopenedasinputTheOpen"F:TEST.xls"ForBinaryAs#1isopenedinbinarymode2,ClosestatementSyntax:Close[filenumber
4、list]Thefilenumberlistparameterisoneormorefilenumbers.Iffilenumberlistisomitted,allactivefilesopenbytheOpenstatementwillbeclosed.Explanation:afteryouopenthefile,youmustclosethefileafteruse.Example:Dim,I,FileNameForI=1,To3FileName=TEST'&I'createsthefilename.OpenFileName,For,Output,As,#I'openthefile.
5、"Print#I","Thisisatest.",writesthestringtothefile.NextI'Close'closesallthreeopenfiles.3,ResetstatementSyntax:ResetFunction:closealldiskfilesopenedwithOpenstatements.Explanation:theResetstatementclosesallactivefilesopenbytheOpenstatementandwritesallofthecontentsofthefilebuffertodisk.Example:DimFileN
6、umberForFileNumber=1,To5Open"TEST"&FileNumber,For,Output,As,#FileNumber"Write#FileNumber","HelloWorld",writesdatatothefile.NextFileNumberReset'closesthefileandwritesthedatainthebuffertodisk.4,FreeFilefunctionSyntax:FreeFile[(rangenumber)]Parameterrangenumberspecifiesarangeinordertoreturnthenextavai
7、lablefilenumberwithinthatrange.Specifying0(default)returnsafilenumberbetween1and255.Specify1toreturnafilenumberbetween256-511.Function:provideafilenumberthathasnotbeenusedyet.Example:DimFNumAsIntegerFNum=Fr