Search code examples
statastata-macros

Use putexcel to insert a string in Excel


I am trying to make an easy to use do file where the user inserts the names of the towns s/he wants to summarize and then Stata:

  • summarizes the towns
  • saves the results in an Excel file
  • exports the names of the towns summarized

I am using a list saved in a local macro since it works well with the inlist() function:

clear
input Date AskingRent str10 Town
2019 12 Boston 
2019 13 Cambridge
2018 14 Boston
2018 15 Cambridge
end

local towns `" "Billerica", "Boston" "'
keep if inlist(City, `towns')
***some analysis

putexcel set "results.xlsx", modify
putexcel A1 = `towns'

I want the Excel file to have "Billerica, Boston" in cell A1.

However, I get an error in the last line of code that says:

nothing found where expression expected


Solution

  • The following works for me:

    clear
    input foo1 str20 foo2
    5 "Billerica"
    6 "Boston"
    7 "London"
    8 "New York"
    end
    
    . local towns `" "Billerica", "Boston" "'
    . keep if inlist(foo2, `towns')
    
    . putexcel set "results.xlsx", modify
    . putexcel A1 = `"`towns'"'
    file results.xlsx saved