I have some Stata code that sometimes produces the error:
program error: code follows on the same line as close brace.
Other times it runs.
What is strange is that the code will run, maybe 80% of the time, but then sometimes it hits this error. If I try it again later or run the same code I have copied in a different folder, it will run again.
The problem could be with the big foreach loop I have, as it crashes around there.
Sometimes it will get through looping a few of the elements (in my case sheets) mentioned there before crashing, but the issue is not with one specific element of the loop, because it will crash at different ones, when it does crash.
The code accepts country names as a user-input, but even for the same country name, sometimes it runs and sometimes I get the error. So the error is not generated by any specific country in the data causing problems vs others.
I am also open to other suggestions to getting the same results as my code in a different way that avoids the error.
The other strange thing is that before I integrated some python code into Stata, I don't recall ever getting the error. But now the code crashes before it reaches the python code.
Here the relevant blocks of code (not the most elegant):
quietly {
* Stata Paths
global path_import "`c(pwd)'"
global path_export "`c(pwd)'/Results"
*********************************************************************************************
* Get country input from user
noisily di in red "Enter the country" _request(ans)
global Country "$ans"
*********************************************************************************************
* Analysis - THIS IS WHERE THE ERROR COMES IN
foreach x in "Biggest Obstacle" "Corruption" "Crime" "Finance" "Firm Characteristics" "Gender" "Informality" "Infrastructure" "Innovation and Technology" "Performance" "Regulations and Taxes" "Trade" "Workforce" {
import excel "$path_import/$datafilename" , sheet("`x'") firstrow clear
keep if Economy=="$Country"
*some basic cleaning after this, just droping and relabling/renaming variables with no braces and no loops
export excel "$path_export/indicator_sector.xlsx" , sheet("`x'" , replace) firstrow(varlabels)
}
python
#basic python code
end
}