VBA子程序必须运行两次才能正确更新依赖单元

时间:2015-11-12 03:19:44

标签: arrays vba excel-vba excel

我正在用VBA-excel编写一个程序,应该: 1 - 确定数组中的数据量(动态数组) 2 - 根据第一个数组内的数字,(1到3)进行一定的计算(圆柱体积= 1,圆锥体积= 2,球体截面体积= 3) 3 - 基于第一个数组中的数字,将使用正确的计算

在D列中打印卷

我目前的计划完成了所有这一切

下一步是保持我拥有的1&2,2&3和3的总数(并打印出来)并保持每个的总计形状总体积。 (即所有气瓶的总容积= xxxx)

再次这一切都很好,除了卷的运行总数。我遇到的问题是在我运行程序一次并且现有值在那里之后,我更改了一个数字(在任何一个列中)并且我必须运行程序两次才能获得正确的数据输出到运行总量。

我认为发生的事情是D列中的音量(计算出的音量)在运行总音量值之前没有更新。但是在查看我的代码时,我不明白为什么在新计算发生之前运行总量检索该数字。

有关如何推迟运行总计直到所有数据都被填充然后收集所有数据的任何想法?

这是我目前的代码:

Sub volumecalc()

totalnum = WorksheetFunction.CountA(Range("A2:A1000"))

ReDim Array1(1 To totalnum)
For i = 1 To totalnum
    Array1(i) = Cells(i + 1, 1)
Next i


ReDim array2(1 To totalnum)
For j = 1 To totalnum
    array2(j) = Cells(j + 1, 2)
Next j


ReDim array3(1 To totalnum)
For k = 1 To totalnum
    array3(k) = Cells(k + 1, 3)
Next k

ReDim array4(1 To totalnum)
For p = 1 To totalnum
    array4(p) = Cells(p + 1, 4)
Next p

Range("D2:D1000") = Clear
Range("G2:G4") = Clear
Range("H2:H4") = Clear


totalvol = 0
totalvol1 = 0
totalvol2 = 0
Count = 0
count1 = 0
count2 = 0

For i = 1 To totalnum

        If Array1(i) = 1 Then
            Cells(i + 1, 4) = WorksheetFunction.Pi * array2(i) ^ 2 * array3(i)
            Count = Count + 1
            Cells(2, 7) = Count
            totalvol = totalvol + array4(i)
            Cells(2, 8) = totalvol
        ElseIf Array1(i) = 2 Then
            Cells(i + 1, 4) = (WorksheetFunction.Pi * array2(i) ^ 2 * array3(i)) / 3
            count1 = count1 + 1
            Cells(3, 7) = count1
            totalvol1 = totalvol1 + array4(i)
            Cells(3, 8) = totalvol1
        ElseIf Array1(i) = 3 Then
            Cells(i + 1, 4) = (WorksheetFunction.Pi * array2(i) ^ 2 * array3(i)) / 2 + (WorksheetFunction.Pi * array3(i) ^ 3) / 6
            count2 = count2 + 1
            Cells(4, 7) = count2
            totalvol2 = totalvol2 + array4(i)
            Cells(4, 8) = totalvol2

        ElseIf Array1(i) < 1 Or Array1(i) > 3 Then
            MsgBox ("Not In Correct Range, Try Again")
        End If
Next i

For j = 1 To totalnum
    If array2(j) <= 0 Then
        MsgBox ("Number Must Be Greater Than 0")
    End If
Next j

For j = 1 To totalnum
    If array3(j) <= 0 Then
        MsgBox ("Number Must Be Greater Than 0")
    End If
Next j


Cells(5, 7) = Count + count1 + count2
Cells(5, 8) = totalvol + totalvol1 + totalvol2
End Sub

1 个答案:

答案 0 :(得分:0)

代码正在将列D中的值读入array4。然后将新计算的值写入D列,但使用array4中的值更新各种总体积变量。这就是为什么总计最初得到旧值以及为什么程序在程序再次运行时正常工作(因为array4使用新值更新)。

不清楚为什么需要array4,所以只需替换出现:

totalvol = totalvol + array4(i)

使用:

totalvol = totalvol + Cells(i + 1, 4).Value
相关问题