VBA中的动态多维数组

时间:2016-10-07 14:52:04

标签: excel vba excel-vba

我在编写此程序时遇到问题。我想定义一个二维数组,让它称之为Cube。数组的大小应取决于名为Number的输入。这样,阵列Cube的尺寸应该是Cube(0到数字,0到数字)。

我希望将Cube(0,0)设置为另一个输入,Starter。从这里开始,我希望从这个起点计算出阵列的其余部分。整个顶行应计算为前一个数字乘以输入X.所以

Cube(1,0) = Cube(0,0)*X
Cube(2,0) = Cube(1,0)*X
Cube(3,0) = Cube(2,0)*X
And so on.

从第2行开始,数组的其余部分应该通过将上面和左边的数字乘以另一个输入Y来计算。例如:

Cube(1,1) = Cube(0,0)*Y
Cube(2,1) = Cube(1,0)*Y
Cube(2,2) = Cube(1,1)*Y
Cube(3,1) = Cube(2,0)*Y
And so on...

一旦定义了所有值,我想将输入Z下面任何数字的值更改为500.例如,if Cube(56,42)< Z,则Cube(53,52)的值将更改为相等500。

最后,我想从最右边的专栏回来,回到Cube(0,0)的起点。如果数组的维度在100处结束,那么:

If Cube(99,0)=500, then keep it as 500, 
Else Cube(99,0)=Cube(100,0)*A + Cube(100,1)*B

为了重复:

If Cube(68,54)=500, then keep it as 500,
Else Cube(68,54)=Cube(69,54)*A + Cube(69,55)*B

2 个答案:

答案 0 :(得分:1)

我认为我正确地遵循了你的逻辑:

Public Sub CubeArray()
Dim Cube()      As Double, _
    i           As Long, _
    j           As Long, _
    X           As Double, _
    Y           As Double, _
    Z           As Double, _
    A           As Double, _
    B           As Double

Const CubeSize = 10 'Change this value to change your array size
ReDim Cube(0 To CubeSize, 0 To CubeSize) As Double
Cube(0, 0) = InputBox("What would you like the first value of the array to be?")
X = InputBox("X =")
Y = InputBox("Y =")
Z = InputBox("Z =")
A = InputBox("A =")
B = InputBox("B =")
For i = 1 To UBound(Cube)
    Cube(i, 0) = Cube(i - 1, 0) * X
    For j = 1 To UBound(Cube)
        Cube(i, j) = Application.Max(Cube(i - 1, j - 1) * Y, Z)
    Next j
Next i
For i = UBound(Cube) - 1 To 0 Step -1
    For j = 0 To UBound(Cube) - 1
        If Cube(i, j) <> Z Then
            Cube(i, j) = Cube(i + 1, j) * A + Cube(i + 1, j + 1) * B
        End If
    Next j
Next i
MsgBox Cube(0, 0)
End Sub

答案 1 :(得分:-1)

这样的事可能吗?

Sub demo()
    Const n As Long = 10

    Range("A1").Resize(n + 1, n + 1).Value = DaCube(n, 1, 2, 3)
End Sub

Function DaCube(n As Long, a As Double, x As Double, y As Double) As Double()
    Dim adCube() As Double
    Dim i As Long
    Dim j As Long

    ReDim adCube(0 To n, 0 To n)
    adCube(0, 0) = a

    For i = 1 To n
        adCube(i, 0) = adCube(i - 1, 0) * x

        For j = 1 To n
            adCube(i, j) = adCube(i - 1, j - 1) * y
        Next j
    Next i

    DaCube = adCube
End Function