Hi,
I've created a file using the filelist command
filelist , dir("C:/Users/mikel/OneDrive/Desktop/results") pattern(recon2022_*.xlsx) save("files.dta")
The resulting file files.dta contains the usual three variables: dirname filename fsize. I've added to it another variable for simpler naming of stata files that will result via
gen fips=substr(filename,11,5)
I'm having trouble importing any of the with a loop, however. I'm sure it's because I don't entirely understand the syntax conventions of loops in Stata. I've tried both forvalues and foreach. For example,
local N=_N
forvalues i=1/'N' {
use "files.dta" in 'i',clear
local f = dirname + "/" + filename
import excel "'f'", sheet("vectors") firstrow clear
local source = fips
.
.
.
gen source="'source'"
save "C:/Users/mikel/OneDrive/Desktop/results/vectors_stata/'source'.dta", replace
}
I've also tried
foreach filename {
clear
import excel "C:/Users/mikel/OneDrive/Desktop/results/'filename'", sheet("vectors") firstrow clear
local source = fips
.
.
.
gen source="'source'"
save "C:/Users/mikel/OneDrive/Desktop/results/vectors_stata/'source'.dta", replace
}
I can import the files one at a time as long as I specify the full directory and filename. There are only 52 of them (one for each of the 50 states, DC, and the US). But I know I must be close and would hate to cave into such rudimentary approach. What am I doing wrong?
I've created a file using the filelist command
filelist , dir("C:/Users/mikel/OneDrive/Desktop/results") pattern(recon2022_*.xlsx) save("files.dta")
The resulting file files.dta contains the usual three variables: dirname filename fsize. I've added to it another variable for simpler naming of stata files that will result via
gen fips=substr(filename,11,5)
I'm having trouble importing any of the with a loop, however. I'm sure it's because I don't entirely understand the syntax conventions of loops in Stata. I've tried both forvalues and foreach. For example,
local N=_N
forvalues i=1/'N' {
use "files.dta" in 'i',clear
local f = dirname + "/" + filename
import excel "'f'", sheet("vectors") firstrow clear
local source = fips
.
.
.
gen source="'source'"
save "C:/Users/mikel/OneDrive/Desktop/results/vectors_stata/'source'.dta", replace
}
I've also tried
foreach filename {
clear
import excel "C:/Users/mikel/OneDrive/Desktop/results/'filename'", sheet("vectors") firstrow clear
local source = fips
.
.
.
gen source="'source'"
save "C:/Users/mikel/OneDrive/Desktop/results/vectors_stata/'source'.dta", replace
}
I can import the files one at a time as long as I specify the full directory and filename. There are only 52 of them (one for each of the 50 states, DC, and the US). But I know I must be close and would hate to cave into such rudimentary approach. What am I doing wrong?
Comment