如何在循环外传递数组?

时间:2013-09-27 19:51:36

标签: arrays excel loops excel-vba vba

我在vba中写了一个sub,但是我不知道如何在循环之外得到 final_array 。我想转置到工作表或保存到全局多维数组。

Dim lent As Long
Dim end_ct As Long


end_ct = 0

Dim final_array() As Variant
ReDim Preserve final_array(11)


final_array(0) = Range("B2").value
final_array(1) = Range("B3").value

j = 8
'Debug.Print final_array(0)
'Debug.Print final_array(1)

For lent = 2 To 11 Step 1


    If lent Mod 2 = 0 Then

        ReDim Preserve final_array(11)
        final_array(lent) = end_pt(end_ct) - strt_pt(end_ct)

        end_ct = end_ct + 1
        'Sheets("SingleEquityHistoryHedge").Cells(47, lent + 1).value = final_array(lent)
    Else

        'gets average over pattern period
        Dim avg_rng As Range
        Set avg_rng = Sheets("SingleEquityHistoryHedge").Range(Cells(strt_pt(end_ct), j), Cells(end_pt(end_ct) - 1, j))
        'Debug.Print sum_rng
        Dim avg_value As Double
        avg_value = avgVal(avg_rng)

        ReDim Preserve final_array(11)
        final_array(lent) = avg_value

       ' Sheets("SingleEquityHistoryHedge").Cells(47, lent + 2).FormulaArray = _
       ' "=AVERAGE(IF(ISNUMBER(" & avg_rng.Address & ")," & avg_rng.Address & "))"

        j = j + 1
    End If




   ' Debug.Print final_array(lent)
'    Debug.Print final_array

'    If lent = 11 Then
'        Range("A" & pos).Select
'        Application.WorksheetFunction.Transpose (final_array)
'    End If

Next lent

我的目标是能够在循环之外打印final_array。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

我没有检查你的代码是否正在填充数组,但是如果它是在循环之后你可以通过使用它将该数组写入任何单元格(我使用A1作为示例

Range("A1").Resize(UBound(final_array) + 1, 1) = _
Application.WorksheetFunction.Transpose(final_array)