在数组中使用VBA函数内的RInterface.GetArrayToVBA

时间:2014-01-09 13:19:20

标签: r excel-vba rexcel vba excel

让Excel电子表格通过RExcel连接到R,并且您想要编写一个调用某些R函数的VBA函数。

在Excel电子表格中,您有几个简单的数组,如下所示:

enter image description here

代码可能是这样的:

Function foo(x As Range, y As Range) As Variant

    RInterface.StartRServer

    If IsNumeric(x) = True Then
        RInterface.PutArrayFromVBA "x", x
    End If

    If IsNumeric(y) = True Then
        RInterface.PutArrayFromVBA "y", y
    End If

    foo = RInterface.GetArrayToVBA("cbind(x, y, y ^ x)")

End Function

,其显而易见的目的是在Excel中返回包含cbind(x, y, y ^ x)的矩阵。

我无法得到它,我得到了奇怪的结果,因为我略微修改了代码:有时输出等于1,有时它等于#VALUE! ...它不会但是,我无法理解这种情况下所需的语法。

1 个答案:

答案 0 :(得分:2)

Function foo(x As Range, y As Range) As Variant

RInterface.StartRServer
RInterface.PutArrayFromVBA "x", x.Value 'you were missing this .Value'
RInterface.PutArrayFromVBA "y", y.Value
foo = RInterface.GetArrayToVBA("cbind(x, y, y ^ x)")

End Function

我省略了您的错误检查,因为它们只会导致其他错误。如果你想做错误检查,请执行错误转到