将Excel VBA阵列转储到工作表中不起作用,

时间:2016-02-14 05:43:56

标签: arrays excel-vba worksheet vba excel

我已经获得了以下代码提取,它假设将数组的内容转储回工作表,但它似乎无法正常工作而且我被卡住了......可能有人请帮忙, 谢谢。

Dim aggressiveDriving(7000) As Variant

For i = 3000 To 7000
    'simple kinematic equation    
    aggressiveDriving(i) = Math.Sqr((((aggressiveDriving(i - 1) / 3.6) ^ 2) + (2 * aggressive_decel))) * 3.6

Next
'at this stage, when I watch the array, it is populated with the expected values in double.
'now writing back to worksheet

With ActiveWorkbook.Worksheets("Current_Driving")
    'if I replace 'aggressiveDriving with '0' then the dumping works with
    'filling 0s
    .Range(.Cells(2, "F"), .Cells(7002, "F")).value = aggressiveDriving
End With

2 个答案:

答案 0 :(得分:2)

与工作表相比,一维数组的方向目前是7000'列'乘1'行',而不是7000'行'乘1'列'。使用工作表的TRANSPOSE function重新定位

With ActiveWorkbook.Worksheets("Current_Driving")
    'if I replace 'aggressiveDriving with '0' then the dumping works with
    'filling 0s
    .Range(.Cells(2, "F"), .Cells(7002, "F")).value = _
        Application.Transpose(aggressiveDriving)
    'I prefer this method of resizing (+1 because it is currently a zero-based index array)
    '.Range("F2").Resize(UBound(aggressiveDriving) + 1, 1) = _
        Application.Transpose(aggressiveDriving)

End With

TRANSPOSE功能有限;通常沿着旧的XLS工作表的维度。

答案 1 :(得分:0)

循环

For i = 0 To 7000
'simple kinematic equation    
aggressiveDriving(i) = Math.Sqr((((aggressiveDriving(i - 1) / 3.6) ^ 2) + (2 * aggressive_decel))) * 3.6 
Next

从0到7000,然后在等式

aggressiveDriving(i) = Math.Sqr((((aggressiveDriving(i - 1) / 3.6) ^ 2) + (2 * aggressive_decel))) * 3.6

在i = 0时,您将访问索引-1中的数组

aggressiveDriving(i - 1)

或者可能是数组大小存在问题。 数组大小为7000, 但你试着写F2:F7002 => 7001(大小)