0

I just started working with Stata and I couldn't figure out the following.

  1. How can I loop over the lists of Excel sheets and the indices. This works fine now.

    clear all
    set more off
    
    local mysheets 1996 2000 2003 2007 2008 2010 
    local indices index1 index2 index3
    
    foreach sheetname of local mysheets {
    
        import excel "C:\stata\Data.xls", sheet(`sheetname') firstrow clear
    
        foreach index of local indices{
           tobit theta index, ll(0) ul(1)
           outreg using "C:\stata\results.doc" , `append'
           local append "append"    
        }
    
    }
    
4
  • 1
    Note that your locals are named differently: mysheets vs. mysheet Commented Jun 28, 2015 at 16:28
  • Also, you are using 'append' before you define it (note the incorrect use of '; I can't figure out how to get SO to allow me to use the proper backtick in this context). And it's not clear why you would define it in the first place (in this context, at least). Commented Jun 28, 2015 at 16:38
  • @Brendan Thank you. Fixed that and it still not working. As for append I found that in that way if the file is not created already it wouldn't append for the first time but would for the rest. Commented Jun 28, 2015 at 17:17
  • Oh I have to change sheetname to ` sheetname' and it works. Commented Jun 28, 2015 at 17:35

1 Answer 1

3

Just to post as an answer (so the question doesn't appear unanswered), since it seems to be a simple coding error:

  • Make sure local macro names are consistent throughout (mysheet vs. mysheets)
  • Use local macro syntax for the argument of foreach (in this case, sheetname) inside of foreach loop
  • If using a local macro to define the append option of outreg, define it before the option is called

    clear all
    set more off
    local mysheets 1996 2000 2003 2007 2008 2010 
    local indices index1 index2 index3
    
    foreach sheetname of local mysheets {
        import excel "C:\stata\Data.xls", sheet(`sheetname') firstrow clear
        foreach index of local indices {
           tobit theta `index', ll(0) ul(1)
           local append "append"    
           outreg using "C:\stata\results.doc" , `append'
        }
    }
    
Sign up to request clarification or add additional context in comments.

2 Comments

Might I add also Brendan to add the ticks on the index macro variable within the nested foreach loop: tobit theta ` index', ll(0) ul(1)
Thanks; was only correcting the items previously identified, but you are of course correct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.