【问题标题】:Run user-defined R function from VBA从 VBA 运行用户定义的 R 函数
【发布时间】:2016-08-17 15:55:09
【问题描述】:

我在尝试调用我在 VBA 中创建的 R 函数时遇到问题。问题不是来自 VBA 和 R 之间的连接,而是当我的 R 代码必须调用我自己的函数时,程序停止了。为了更清楚,这里是R代码:

args = commandArgs(trailingOnly=T)
sink('Y:/Documents/BC10.txt', append=F, type = "output",split=TRUE)
source("Y:/Documents/myfunction.R")
cat('TEST !!')
simul = args[1]
level = args[2]
spd1 = args[3]
spd2 = args[4]
spd3 = args[5]
date_valo = toString(args[6])
swap_rate = args[7]
l1 = 0
u1 = 0.03
rho2 = 0.5
cat('\nparameters are: ', simul,  level, spd1 , spd2, spd3, date_valo, swap_rate)

PV_eq=PV_eq=myfunction(l1,u1,spd1,rho2,simul,level, date_valo, swap_rate)
cat(PV_eq)
sink()

当我运行我的 VBA 代码时,程序在显示文本文件“BC10.txt”中的参数方面做得很好,但它不显示 PV_eq。所以,我认为程序无法调用我的用户定义函数“myfunction”。

有人知道我遇到的问题吗?也许,我必须在我的 VBA 代码(或 R 代码)中添加一些内容,以便 VBA 考虑用户定义的函数?

【问题讨论】:

  • 我根本不是“R”程序员,但你的“myfunction”代码是什么?也许问题出在那儿?
  • 如果您的问题仅与 R 有关,请删除 VBA 和 Excel-VBA 标签。如果您对VBA 中的R 有疑问,请将VBA 代码附加到问题中。另外,您能否详细说明您用于执行R 代码的R 主机:RExcelR via SQLcalling Rscript 或其他一些意思?

标签: r vba excel rexcel


【解决方案1】:

感谢您的回答。

我认为问题不在于我的 R 代码,因为当我在 R 中运行函数“myfuntion”时,它可以工作。

我正在使用 Rexcel 来执行我的 R 代码。这是 VBA 代码:

Sub Compute_BC()

将外壳暗淡为对象 设置 shell = VBA.CreateObject("WScript.Shell") 将 waitTillComplete 调暗为布尔值:waitTillComplete = True 将样式暗淡为整数:样式 = 1 将错误代码调暗为整数 暗淡路径为字符串

Dim simul, level As Variant
Dim spd1, spd2, spd3, swap_rate As Variant
Dim date_valo As String

simul = BC.Range("B6").Value

level = BC.Range("B4").Value

spd1 = BC.Range("B13").Value

spd2 = BC.Range("C13").Value

spd3 = BC.Range("D13").Value

date_valo = BC.Range("B1").Value

swap_rate = BC.Range("B5").Value

path = """" & Cells.Range("RhomeDir") & """ """ & Cells.Range("MyRscript") & """" & " " & simul & " " & level & " " & spd1 & " " & spd2 & " " & spd3 & " " & date_valo & " " & swap_rate

errorCode = shell.Run(路径、样式、waitTillComplete)

结束子

Rmq:我用一个简单的 R 文件测试了这个 VBA 代码,它工作正常。问题出现在我的 R 文件中,调用了我定义的函数。

【讨论】:

    猜你喜欢
    • 2019-12-16
    • 2015-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多