I am trying to compile data from a series of Excel workbooks and worksheets, while I have something that works it is rather inefficient coding. I have got company data from 30 companies in Excel format, and these Excel workbooks are in (relatively) consistent structure. The approach I've taken is to simply list each company every time I need to use that foreach loop. For example:
However rather than listing all 30 company names every time, I thought I could apply a local macro, but regardless of how I structure the local macro I cannot seem to make it work.
This does nothing. I tried adding extra " " in the loop, but get an r(100) using error. Any advice on what I am doing wrong, or if it can be done. Any assistance would be much appreciated
PS - I did consider using a local files macro, and had it working to an extent, but because I also use the company loop names to define variables and save data file makes this method not ideal as it loops the full file name rather than the company name
Code:
foreach company in "Company Alpha" "Company Beta" "Company Gamma" { import excel "`company'", sheet("sheetname") clear *code applicable to each company }
Code:
local names `" "Company Alpha" "Company Beta" "Company Gamma" "' foreach company in `names' { import excel "`company'", sheet("sheetname") clear *code applicable to each company }
PS - I did consider using a local files macro, and had it working to an extent, but because I also use the company loop names to define variables and save data file makes this method not ideal as it loops the full file name rather than the company name
Code:
local files : dir "C:\Users\MichaelW\Desktop\Stata working drive" files "*.xlsx" foreach company in `files' { *code applicable to each company generate company="`company'" generate year="`year'" save "C:\Users\MichaelW\Desktop\Stata working drive" files\_`company'.dta", replace }
Comment