特定位置 sheet 的二维数组值

2D array values to sheet at specific location

我正在尝试将二维数组的值添加到作品中sheet,从某个单元格开始。
例如,在单元格 A1 中,我键入公式 =testArray2Sheet(D7)
预期的结果是值出现在 sheet 上,第一个值在单元格 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

要将数组移动到 sheet,请将数组公式 (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

首先高亮显示一个单元格,比如单元格 B5D22
然后单击公式栏并输入数组公式:

=testArray2Sheet()

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

你应该看到:

输入公式的单元格块决定了数组的目标。