Rushil Zutshi
Rushil Zutshi

Reputation: 133

Conflict of global macro and loop

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.

Upvotes: 0

Views: 324

Answers (1)

user8682794
user8682794

Reputation:

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'
}

Upvotes: 1

Related Questions