VBA数组逆

时间:2018-12-11 01:10:27

标签: arrays excel vba excel-vba inverse

大家好!

我正在Excel VBA中尝试从方形阵列的电子表格中获取一些值,然后将其反转。我有以下代码

Private Sub CommandButton1_Click()
Dim A As Variant
Dim i As Integer, j As Integer
ReDim A(1 To 3, 1 To 3) As Double

For i = 1 To 3
    For j = 1 To 3
        A(i, j) = Cells(i, j).Value      
    Next j
Next i

A = Application.WorksheetFunction.MInverse(A)

End Sub

在此行:

A = Application.WorksheetFunction.MInverse(A)

我得到了错误:

  

运行时错误1004:应用程序定义或对象定义的错误

有人可以协助我吗? 预先谢谢你

2 个答案:

答案 0 :(得分:3)

尝试下面的代码从单元格A1读取3×3数组,然后将反函数写在单元格A5上。

Private Sub CommandButton1_Click()
    Dim A() as Variant, B() as Variant
    A = Range("A1").Resize(3,3).Value
    B = WorksheetFunctions.MMinverse(A)
    Range("A5").Resize(3,3).Value = B
End Sub

不需要遍历每个单元格,这是一个缓慢的操作。使用Range().Resize().Value语法通过一个命令读取和写入整个表。

答案 1 :(得分:1)

您可能正在尝试将病态矩阵求逆。我在一个简单的示例上尝试了您的代码:

Sub dural()

    Dim A As Variant
    Dim i As Integer, j As Integer
    ReDim A(1 To 3, 1 To 3) As Double

    For i = 1 To 3
        For j = 1 To 3
            A(i, j) = Cells(i, j).Value
        Next j
    Next i

    A = Application.WorksheetFunction.MInverse(A)

    For i = 1 To 3
        For j = 1 To 3
            Cells(i + 5, j + 5).Value = A(i, j)
        Next j
    Next i
End Sub

并得到:

enter image description here

这似乎是正确的。 (两个矩阵的乘积非常接近单位矩阵)