arrays - 二维数组值在特定位置打印

标签 arrays vba excel range

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

最佳答案

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

你应该看到:

enter image description here

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

关于arrays - 二维数组值在特定位置打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30514944/

相关文章:

arrays - 获取作为引用传递的数组的第一个元素的 Perl 脚本

vba - 在 Word VBA 上用 StoryRange 替换文本使其暂时无响应

Python csv 模块与 pandas.read_csv 和 Python xlrd 与 pandas.read_excel

c++ - 在 C++ 中作为参数传递时,数组隐式转换为容器类

java - 检查 arrayList 是否包含数组

c++ - 检查字符串数组中是否存在字符串的最快方法是什么?

vba - Excel ActiveX 列表框随着每次更新而缩小

excel - 如何增加复选框的大小?

Excel 和在两个下拉列表之间更改值

excel - 如何使用 VBA 将数据透视表过滤器放置在彼此上方?