【问题标题】:Run macro with Rexcel使用 Rexcel 运行宏
【发布时间】:2014-03-27 14:51:56
【问题描述】:

我在 VBA 中使用 Rexcel 运行宏:

Sub create_efficient_frontier()

 RInterface.StartRServer

 Sheets("Analys").Range("A52:K82").ClearContents

 RInterface.PutDataframe "datat", Range("ChosenData!X181:AD352")
 RInterface.PutArray "startdate", Range("Analys!K2")
 RInterface.PutArray "enddate", Range("Analys!K3")

 RInterface.RunRFile "C:/Users/Documents/EffFront.R"

 RInterface.GetDataframe "hmz$pweight", Range("Analys!A51:E76")

End Sub

源代码为:

myfront=function(datat,startdate,enddate){
  library(fPortfolio)
  datat=datat[startdate:enddate,]
  datanew=datat[sapply(datat[1,], function(x) !any(is.na(x)))] 

  datatss=as.timeSeries(datanew,datanew[,1])

  Spec = portfolioSpec()
  Constraints = "Long-Only"
  globminhfrxmed=minvariancePortfolio(
    data = datatss,
    spec = Spec,
    constraints = Constraints)

  setNFrontierPoints(Spec) <- 25
  globminfrontier <- portfolioFrontier(datatss,Spec, Constraints)

  thelisttoret<-vector(mode="list")

  pweights<-globminfrontier@portfolio@portfolio$weights
  pweights<-data.frame(pweights)
  names(pweights)=colnames(globminfrontier@portfolio@portfolio$covRiskBudgets)
  thelisttoret[["pweights"]]<-pweights

  tret<-globminfrontier@portfolio@portfolio$targetReturn[,1,drop=FALSE]
  thelisttoret[["tret"]]<-tret

  trisk<-globminfrontier@portfolio@portfolio$targetRisk[,2,drop=FALSE]
  thelisttoret[["trisk"]]<-trisk

  return(thelisttoret)
}

hmz=myfront(datat,startdate,enddate)

这似乎可行,但第一行(名称应该在哪里)是#RError。但是代码在 R 中可以正常工作。

这很奇怪,因为当我在网上阅读时,它说

RInterface.GetDataframe(varname,range)
将 R 变量 var(需要是数据框)的值放入 Excel 范围范围内,将变量名称放在范围的第一行。

【问题讨论】:

  • 好吧,在你的 R 代码中你运行:thelisttoret[["pweights"]]&lt;-pweights(注意复数 pweights)而在你的 Excel 宏中你引用 hmz$pweight(单数)。会不会是这个问题?
  • @jlhoward 哈哈典型的:) 谢谢!

标签: r excel vba rexcel


【解决方案1】:

答案转到@jlhoward。

您的 VBA 代码中有错字。 而不是:

RInterface.GetDataframe "hmz$pweight", Range("Analys!A51:E76")

你应该使用

RInterface.GetDataframe "hmz$pweights", Range("Analys!A51:E76"),

即在您的 R 代码中,您使用 pweights(复数),但在 VBA 代码中,您使用 pweight(单数)。

【讨论】:

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