1

I need to make some operations with many Excel files with long names of the type "Saratov Region.xls" (I mean that names of these files contain one or more blank spaces).

I tried to write something like

global reglist = "Saratov Region Samara Region ..."

and then write

foreach var of global reglist {
   import excel `var'.xls, clear
   <other commands>
}

but Stata reads "Saratov", "Region" and so on as separate elements of the list, so this does not work.

I tried to write somthing like

global reglist = "Saratov Region" "Samara Region" ...

but Stata also treats "Saratov", "Region" and so on as separate elements of the list, and writes error meassage "invalid "Samara Region".

How should I define this list for this to work?

2 Answers 2

0

It's a little tricky to use the right quoting, but here's an example:

global reglist = `" "Saratov Region" "Samara Region"  "'
foreach var of global reglist {
 di "`var'"
}

Basically, wrap individual region names in double quotes and then wrap everything with the additional local quotation.

0
0

The problem one level back is reading in a series of files with the twist that the filenames may contain spaces. Many people avoid that by never including spaces in filenames, but naturally the filenames may be beyond your control.

A better solution than populating a global (or local) macro by typing in filenames is to get Stata to collect the filenames automatically. You can use a local macro function dir ... files. Start at help macro and look for macro functions.

A wrapper for that is fs from SSC with which you can do things like

fs *.xls

with the result that the filenames will be gathered into r(files) so that you can then loop over its elements.

foreach f in `r(files)' { 
   import excel "`f'", clear
   <other commands>
}

That way there are no work-arounds for spaces, beyond using " " in the body of the loop.

1
  • Thank you so much, it works well after installing fs. Thank you!!! Commented Jun 21 at 19:58

Not the answer you're looking for? Browse other questions tagged or ask your own question.