excel - Can someone explain how a While Loop using the Dir function works in VBA? -


i'm new vba , needed make script work. script in directory , import .txt files found new worksheet in workbook. i.e. if there 20 .txt files, end 20 worksheets. found code online perfectly, want to. problem is, don't understand how works. i've never used dir function, , appears loop focuses on this, i'm still confused how looping 1 file next. if me understand, or add comments code, helpful. thanks.

code is:

    sub loadfiles() dim idx integer dim fpath string dim fname string dim ws worksheet idx = 0 fpath = "c:\myfolderlocation" fname = dir(fpath) while (len(fname) > 0)     idx = idx + 1     sheets.add.name = fname     activesheet.querytables.add(connection:="text;" _       & fpath & fname, destination:=range("a1"))         .name = "a" & idx         .fieldnames = true         .rownumbers = false         .filladjacentformulas = false         .preserveformatting = true         .refreshonfileopen = false         .refreshstyle = xlinsertdeletecells         .savepassword = false         .savedata = true         .adjustcolumnwidth = true         .refreshperiod = 0         .textfilepromptonrefresh = false         .textfileplatform = 437         .textfilestartrow = 1         .textfileparsetype = xldelimited         .textfiletextqualifier = xltextqualifierdoublequote         .textfileconsecutivedelimiter = false         .textfiletabdelimiter = false         .textfilesemicolondelimiter = false         .textfilecommadelimiter = false         .textfilespacedelimiter = false         .textfileotherdelimiter = ","         .textfilecolumndatatypes = array(1, 1, 1)         .textfiletrailingminusnumbers = true         .refresh backgroundquery:=false         fname = dir     end wend 

end sub

the dir function returns, 1 @ time, filenames directory.

when call dir() path directory argument, return first filename directory.

when call dir() without argument, return next filename directory until there no more files, in case null name returned.

so in order process files in directory need dir(path) once, followed dir() long returns name.

how test if name returned? fname>"" way, here use len(fname)>0 len function takes string argument , returns length of string.

so comes "as long there files" part. implemented loop structure while condition ... things end while

in case

while (len(fname) > 0) ... fname=dir end while


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -