从VBA调用Matlab函数

时间:2018-10-10 15:07:34

标签: excel vba matlab

我正在尝试从VBA调用Matlab函数,并编写了一个简单的示例代码来进行尝试。该代码尝试计算2x2随机矩阵的行列式。

Sub Code()
    Dim DMat(1 To 2, 1 To 2) As Double, DetA As Object, Matlab As Object
    Upper = 1000
    Lower = 10
    For i = 1 To 2
        For j = 1 To 2
            DMat(i, j) = ((Upper - Lower) * Rnd + Lower)
            Sheet1.Cells(i + 1, j) = DMat(i, j)
        Next
    Next

    Set Matlab = CreateObject("Matlab.Application")

    On Error GoTo Errorfound
    Matlab.PutWorkspaceData "A", "base", DMat
    Matlab.Execute "Result = det(A);"
    DetA = Matlab.GetVariable("Result", "base")

Errorfound:
    With Err
        MsgBox "Source: " & .Source & vbCrLf & "Desc: " & .Description, _
            vbCritical, "Error " & CStr(.Number)
        End With
    Sheet1.Range("A6").Value = DetA
End Sub

在包含GetVariable命令的行上收到运行时错误440 。我试图获取描述,但始终为空白。

enter image description here

我尝试使用GetWorkspaceData代替GetVariable,但是结果是一样的。

我要去哪里错了?

1 个答案:

答案 0 :(得分:1)

全部, 我终于设法找到了解决方案。这是代码:

Sub Code()

Dim DMat(1 To 2, 1 To 2) As Double, MatLab As Object
Dim DbR(1 To 1) As Double
Dim DbI(1 To 1) As Double

Upper = 100
Lower = 10

For i = 1 To 2
    For j = 1 To 2
        DMat(i, j) = ((Upper - Lower) * Rnd + Lower)
        Sheet1.Cells(i + 3, j) = DMat(i, j)
    Next
Next

Set MatLab = CreateObject("Matlab.Application")
MatLab.PutWorkspaceData "A", "base", DMat
Result = MatLab.Execute("D = det(A) ")
MatLab.GetFullMatrix "D", "base", DbR, DbI
Sheet1.Range("A8").Value = DbR

End Sub