2D数组值在特定位置的工作表

时间:2015-05-28 18:56:18

标签: arrays excel vba excel-vba range

我试图将2D数组的值放到工作表上,从某个单元格开始。
例如,在单元格A1中,我键入公式=testArray2Sheet(D7)
预期结果是值显示在工作表上,第一个值位于单元格D7中,跨越18行,跨越3列。

我当前的代码只是在此行停止执行:targetRange.Value = arr并退出而不会发出警告或错误。
单元格A1只是说#VALUE 我不知道为什么......

Function testArray2Sheet(firstCell As range)
    Dim ret As Boolean 'dummy return value
    Dim targetRange As range
    Dim lastCell As range
    Dim arr As Variant
    Dim rows, cols As Integer
    Dim i, j As Integer

    'Determine size of array
    rows = 18
    cols = 3

    'Make sure the array has the new dimensions
    ReDim arr(1 To rows, 1 To cols)

    'Fill the array with values
    For i = 1 To 18
    For j = 1 To 3
        arr(i, j) = i * j
    Next
    Next

    'firstCell is the top-left corner of the targetRange
    'Now determine the bottom-right corner of the targetRange
    Set lastCell = firstCell.Offset(rows, cols)

    'Create the targetRange
    Set targetRange = range(firstCell, lastCell)

    'Put the values of the array to the targetRange
    'This should me the values appear in the worksheet
    targetRange.Value = arr

    'Return a dummy value, because a function needs to return something
    testArray2Sheet = ret
End Function

1 个答案:

答案 0 :(得分:3)

要将数组移动到工作表中,请将数组公式(UDF)放在要接收值的单元格中。说UDF是:

Function testArray2Sheet()
    Dim targetRange As Range
    Dim arr As Variant
    Dim rows As Long, cols As Long
    Dim i As Long, J as Long

    rows = 18
    cols = 3

    'Make sure the array has the new dimensions
    ReDim arr(1 To rows, 1 To cols)


    For i = 1 To 18
      For j = 1 To 3
          arr(i, j) = i * j
      Next
    Next

    testArray2Sheet = arr
End Function

首先点亮一个细胞块,比如细胞 B5 D22
然后单击公式栏并输入数组公式:

=testArray2Sheet()

(使用 Ctrl + Shift + 输入而不仅仅是 Enter 键)

你应该看到:

enter image description here

这是输入公式的单元格块,用于确定数组的目标。