VBA数组:根据条件添加元素

时间:2013-04-06 22:19:50

标签: arrays loops excel-vba vba excel

我想收集数组中循环的结果。理想情况下,我会保留第一个循环的结果,并将其与第二个循环的结果进行比较。如果第二个循环的结果更好,那么我想保留第二个循环,将它与第三个循环比较,依此类推。关于如何做到这一点的任何想法?这是我到目前为止的摘录:

For Each ccell In pcrange
If ccell.Cells.Value = 0 Then
    For Each agecell In agerange
    If agecell.Cells.Value < 0.5 And agecell.Offset(0, 5).Value > 1 Then
    tmpyr = agecell.Offset(0, 1)
    srchyr = ccell.Offset(0, -6)
    tmpval = agecell.Offset(0, 2)
    tmpdiff = Abs(tmpyr - srchyr)
    arrindx = arrindx + 1

    End If

    tmparray = Array(tmpdiff, tmpval) 'need redim to hold more than 2 values? why are subsequent elements empty?
    ReDim Preserve tmparray(2 * arrindx - 1)
   'minarr = IIf(tmparray(2) > tmparray(0), tmparray(1), tmparray(3)); want to extract corresponding tmpval from array onto sheet if tmpdiff is the min of the entire loop; change to store better result each time
    Next 
End If
Next

1 个答案:

答案 0 :(得分:0)

定义tmparray应该是这样的:

tmparray(UBound(tmparray, 1)) = Array(tmpdiff, tmpval) 'add values to last place
ReDim Preserve tmparray(UBound(tmparry, 1) + 1) 'add another place to the array

找到新的分钟应该放在ReDim

之后
If UBound(tmparray, 1) <= 2 then 
    minarr = tmpval
ElseIf tmparray(UBound(tmparray, 1) - 1, 0) < tmparray(UBound(tmparray, 1) - 2, 0) then 
    minarr = tmparray(UBound(tmparray, 1) - 1, 1)
end if