【问题标题】:stata: sheet name not exist when savingstata:保存时工作表名称不存在
【发布时间】:2021-10-18 20:29:55
【问题描述】:

我正在编写一个stata程序访问excel文件中的多个工作表,对它们进行操作后,我尝试保存结果,但它显示工作表名称不存在(找不到Cabo,r (111)) 我的代码是这样的:

clear
foreach sheet in "Cabo" "Ga" "Inha" {
import excel using "filename.xlsx", sheet("`sheet'") firstrow
//here are operations//
if `sheet' == "Cabo" {
    save test1018
    }
else {
    append using test1018.dta
    save test1018
    }
}

有谁知道我做错了什么?谢谢!!

【问题讨论】:

  • 您需要在 -if- 语句中的两个元素周围加上“”。当 Stata 认为它被告知要查找名为 -Cabo- 的变量或标量时,循环失败。至少还有一个错误,需要在第二个和第三个 -save-s 上添加 -replace- 选项。
  • 谢谢尼克!我将代码更改为 --"sheet" == "Cabo"--,并按照您的建议添加了“替换”。现在它返回错误 --file Cabo not found-- r(601)..
  • 你仍然需要单引号,就像在你的 -import- 命令中一样。
  • …双引号…

标签: excel stata


【解决方案1】:

您还需要在追加后保存数据时包含, replace。您还可以通过在循环之前保存一个空数据集来简化代码。然后每个工作表都将附加到此数据集,您不必将第一个工作表与后续工作表区别对待。

*Save an empty dataset to append to
clear
save test1018.dta, replace emptyok

foreach sheet in "Cabo" "Ga" "Inha" {
    import excel using "filename.xlsx", sheet("`sheet'") firstrow
    //here are operations//
    append using test1018.dta
    save test1018.dta, replace
}

【讨论】:

    【解决方案2】:

    @TheIceBear 在这里指出了很好的技术。

    这个答案的重点是,对于三张纸来说,循环不是必需的。这也应该有效,但取决于我们无法检查的文件的详细信息。

    import excel using "filename.xlsx", sheet("Cabo") firstrow clear 
    save test1018
    
    import excel using "filename.xlsx", sheet("Ga") firstrow clear 
    append using test1018
    save test1018, replace 
    
    import excel using "filename.xlsx", sheet("Inha") firstrow clear 
    append using test1018 
    save test1018, replace 
    

    我同意这是我在不编写循环的情况下所能达到的程度,但代码清晰、透明并且可能会花费您更少的时间来编写。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多