Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Looping over letters stored in a global to use putexcel - can not access a global

    Hi everyone,

    I need to loop over the different values of a global to export results in excel using putexcel.

    The problem is that I cannot access the letters inside the global. In the following code, the problem is that letter3 can not be displayed.
    You can play around by changing the number in the local letter_counter to see that I can actully access the values of the global c(ALPHA), but not the values of master_letters.
    Many thanks to anyof you who will help me.

    *Loop to define master global of letters to export results in excel with putexcel
    global master_letters = ""
    global slave = "`c(ALPHA)' "
    foreach letter_slave in `c(ALPHA)' {

    foreach letter in `c(ALPHA)' {
    global master_letters = "$slave" + "`letter_slave'" +"`letter' "
    global slave = "$master_letters"

    }
    }
    *These will be the excel columns
    display("$master_letters")

    local letter_counter= 5
    local letter2 : word `=`letter_counter'' of `c(ALPHA)'
    local letter3 : word `=`letter_counter'' of `master_letters'
    dis "`letter2'"
    dis "`letter3'"











  • #2
    The error is in
    Code:
    local letter3 : word `=`letter_counter'' of `master_letters'
    You are referencing master_letters as if it were a local macro. But you have never defined such a local macro. You have defined a global macro master_letters. So the code should be
    Code:
    local letter3 : word `=`letter_counter'' of $master_letters'
    Actually, you can even simplify that. There is no need for the `=`letter_counter'' syntax here, because `letter_counter' is defined as a number and does not require any further evaluation of an expression. So you can just do:
    Code:
    local letter3 : word `letter_counter' of $master_letters
    Also, I'm not sure exactly how you're planning to use these results, but rather than building up your own macro of possible column names, you might want to use Sergiy Radyakin's -excelcol- program, available from SSC to get column names corresponding to the values of `letter_counter'.

    Finally, all of the global macros you have defined here would work equally well, at least as far as anything you have shown here as local macros. Local macros being a safer programming practice, I would change the globals to locals.


    Comment

    Working...
    X