将 Excel VBA 数组转储到工作表中不起作用,

Dumping Excel VBA Array into worksheet not working,

我有下面的代码摘录,它应该将数组的内容转储回工作表,但它似乎不起作用,我被卡住了..有人可以帮忙吗,谢谢。

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

循环播放

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 (size)

与工作表相比,一维数组的方向目前是 7000 'columns' x 1 'row',而不是 7000 'rows' x 1 'column'。使用工作表的 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 工作表的尺寸线。