初始化电子表格,计算顺序

时间:2013-04-14 19:13:06

标签: excel-vba vba excel

我编写了一个VBA代码,它解决了一组代数方程,其系数矩阵是三对角线(称为Thomas算法)。方程式具有

形式

A(ⅰ)X(I-1)+ B(ⅰ)X(I)+ C(I)X(I + 1)= R(I)

A,B,C和R的值传递给返回X值的函数.VBA代码如下。

Option Base 1
Function TRIDI(ByVal Ac As Range, ByVal Bc As Range, ByVal Cc As Range, _
ByVal Rc As Range) As Variant
Dim BN As Single
Dim i As Integer
Dim II As Integer
Dim A() As Single, B() As Single, C() As Single, R() As Single, X() As Single
N = Ac.Rows.Count
ReDim A(N), B(N), C(N), R(N), X(N)
For i = 1 To N
A(i) = Ac.Parent.Cells(Ac.Row + i - 1, Ac.Column)
B(i) = Bc.Parent.Cells(Bc.Row + i - 1, Bc.Column)
C(i) = Cc.Parent.Cells(Cc.Row + i - 1, Cc.Column)
R(i) = Rc.Parent.Cells(Rc.Row + i - 1, Rc.Column)
Next i
A(N) = A(N) / B(N)
R(N) = R(N) / B(N)
For i = 2 To N
II = -i + N + 2
BN = 1 / (B(II - 1) - A(II) * C(II - 1))
A(II - 1) = A(II - 1) * BN
R(II - 1) = (R(II - 1) - C(II - 1) * R(II)) * BN
Next i
X(1) = R(1)
For i = 2 To N
X(i) = R(i) - A(i) * X(i - 1)
Next i
TRIDI = Application.WorksheetFunction.Transpose(X)
End Function

该函数适用于线性方程。如果方程是非线性的,例如下面的三个方程式

X(1)= 1

X(1)-2X(2)+ X(3)= 3 + X(1)^ 2

X(1)+ X(3)= 2

使用Excel的迭代功能迭代获得解决方案,如下所示。 (我还不能发布图片,因为这是我的第一篇文章。如果你给我发电子邮件,bumedoc @ gmail.com,我也可以发给你电子表格)

     A    B    C     D                  E

1    A    B    C     R                  X

2    0    1    0     =1          =TRIDI(A2:A4,B2:B4,C2:C4,D2:D4)

3    1   -2    1     =3+E2^2     =TRIDI(A2:A4,B2:B4,C2:C4,D2:D4)

4    1    1    0     =2          =TRIDI(A2:A4,B2:B4,C2:C4,D2:D4)

但是,保存电子表格并再次打开后,我得到#value! E2出错:E4和D3。我假设在打开电子表格时,Excel尝试初始化具有循环引用的单元格并使其混淆。有没有人解决这个问题?

1 个答案:

答案 0 :(得分:1)

=3+E2^2替换=IFERROR(3+E2^2,0)对我有用。