【问题标题】:2D array values to sheet at specific location二维数组值在特定位置打印
【发布时间】:2015-05-28 18:56:17
【问题描述】:

我正在尝试将二维数组的值添加到工作表中,从某个单元格开始。
例如,在单元格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

【问题讨论】:

  • 您正在尝试在函数中写入工作表?除了This,您不能使用函数写入不同的单元格
  • @TimWilliams:你的寿命很长!当我在上面的评论中链接你的一个帖子时,我只是在想你
  • 您是否考虑过使用Sub 而不是Function
  • 请注意,只要您从 Sub 而不是作为 UDF 调用它,您当前的代码就可以正常工作。 Sub test(): testArray2Sheet [a1]: End Sub 会工作。如果你这样做,你还会发现你的输出数组是 1 行和列太大。需要做.Offset(rows-1, cols-1)Offset 是要移动的行数。或者,您可以使用 firstCell.Resize(rows, cols).Value = arr 并跳过 lastCelltargetRange 业务。

标签: arrays vba excel range


【解决方案1】:

要将数组移动到工作表中,请将数组公式 (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 而不仅仅是 Enter 键)

你应该看到:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多