0

I'm trying to automate the process of running through a bunch of files that are sequentially named, manipulate them all in the same way and then save them.

I thought that using a forvalues loop with a global macro would be the best way to do this in Stata.

My code is something like:

global s=1988
forvalues i=${s}/2018 {
import excel "${s}.xlsx", sheet("Data") firstrow clear 
.
.
.
save ${s}, replace
}

However, this gives me the error:

program error: code follows on the same line as open brace

It seems that Stata is reading the curly brace for the global macro as the start of the loop. I tried different variations of the loop to get around this but to no avail. Since I am using clear within the loop, I can't use a local macro or it goes into an infinite loop.

  • 1
    I don't know what you're doing differently in the middle of the loop, but you're saving to the same dataset. Hence only your last import will have any effect. You probably mean to refer to different spreadsheet files, not always that for 1988. – Nick Cox Sep 13 '18 at 17:21

1 Answers1

1

I have come across this issue before. For some reason Stata gets confused about the number of curly braces. If you remove them, the forvalues loop works as expected:

global s = 1988
forvalues i = $s / 2018 {
    display `i'
}

1988
1989
1990
1991
.
.
.
2016
2017
2018

You can also nest the global macro s inside a local macro:

local s = ${s}
forvalues i = 1 / `s' {
    display `i'
}
  • 1
    There is no discernible good reason to use a global macro for a number like 1988. Use a local macro instead or just the literal value 1988. – Nick Cox Sep 13 '18 at 17:11