2015-03-13 59 views
0

我有一種情況,我需要導入目錄中的所有文件並追加它們。我的代碼是這樣的Stata:循環並追加

local files : dir "C:\Users\xx" files "*.xls" 

local n: word count `files' 
tokenize ``files'' 

cd "C:\Users\xx" 

forval k =1/`n'{ 

foreach file in `files' { 
    import excel "`file'", sheet("Time Sheet") clear 

drop in 3 

if `k' == 1 { 
    di in red `k' 
     save "C:\Users\xx\master.dta", replace 
    } 
    else { 
    append using "C:\Users\xx\master.dta" 
    } 
    save "C:\Users\xx\master.dta", replace 
} 
} 

然而,當我使用此代碼似乎運行一個額外的循環(* forval K = 1 /`N'*)創造重複的條目。因爲我需要它作爲append命令,所以我無法擺脫那些代碼。我想知道是否有辦法緩解這個問題。

+0

這裏使用反斜槓也是[不鼓勵](http://www.stata-journal.com/article.html?article=pr0042)。 – 2015-03-13 17:57:02

回答

1

雙迴路引起的問題:

local files : dir "D:/Datos/rferrer/Desktop/statatemps" files "test*.xls" 

cd "D:/Datos/rferrer/Desktop/statatemps" 

local counter = 1 
foreach file in `files' { 

    import excel "`file'", sheet("Hoja1") firstrow clear 

    if `counter' == 1 { 
     di in red `counter' 
     save "D:/Datos/rferrer/Desktop/statatemps/master.dta", replace 
    } 
    else { 
     append using "D:/Datos/rferrer/Desktop/statatemps/master.dta" 
     save "D:/Datos/rferrer/Desktop/statatemps/master.dta", replace 
    } 

    local counter = 0 
} 

list 

你不使用由tokenize創建的令牌,這樣你就可以將其刪除。

較短的將是:

clear 
set more off 

local pathdir "D:/Datos/rferrer/Desktop/statatemps" 

local files : dir "`pathdir'" files "test*.xls" 

save "`pathdir'/master.dta", emptyok replace 
foreach file in `files' { 

    import excel "`file'", sheet("Hoja1") firstrow clear 
    append using "`pathdir'/master.dta" 
    save "`pathdir'/master.dta", replace 

} 

list 

您可能需要閱讀help quotes如果由於某種原因,你有「怪異」的文件名(因爲它是無論如何讀好)。