gpt4 book ai didi

Excel VBA将数组数组传递给函数

转载 作者:行者123 更新时间:2023-12-04 22:06:45 25 4
gpt4 key购买 nike

我有一个创建数组数组的函数,以及一个应该获取结果数组并将其写入电子表格的函数。我找不到允许我将数组数组传递给第二个函数的语法......你能帮忙吗?

例如,如果 arr1 和 arr2 每个包含 24 个项目(它们总是包含相同数量的项目),我希望得到的数组是一个 24 x 2 大小的二维数组,并且我希望将得到的 2 x 24 表写入电子表格,例如范围 A1:B24

这是我的代码:

创建数组数组的函数:

Function GetCellDetails(dict1 As Dictionary, dict2 As Dictionary)   As Variant

Dim arr1, arr2
arr1 = dict1.Items
arr2 = dict2.Items

GetCellDetails = Array(arr1, arr2)

End Function

将其写入电子表格的函数:
Sub WriteCellDataToMemory(arr As Variant, day As Integer, cellId As Integer, nCells As Integer)
row = CellIdToMemRow(cellId, nCells)
col = DayToMemCol(day)

arrSize = UBound(arr, 2) 'compiler error
Range(Cells(row, col), Cells(row + arrSize , col + 2)) = Application.Transpose(arr)

End Sub

调用函数的代码:
Dim CellDetails
CellDetails = GetCellDetails(dict1, dict2)
WriteCellDataToMemory CellDetails, day, cellId, nCells

我收到以下编译器错误:
arrSize = UBound(arr, 2) ,因为编译器不知道 arr 是一个 2 dim 数组...
谢谢,

最佳答案

创建的CellsDetails实际上是一个一维数组。 Ubound(arr)做这项工作。

Sub Main()

Cells.ClearContents

Dim d1 As New Dictionary
Dim d2 As New Dictionary

d1.Add 1, "1"
d1.Add 2, "2"
d2.Add 3, "3"
d2.Add 4, "4"

Dim CellDetails
CellDetails = GetCellDetails(d1, d2)

WriteCellDataToMemory CellDetails

End Sub

Function GetCellDetails(dict1 As Dictionary, dict2 As Dictionary) As Variant

Dim arr1, arr2
arr1 = dict1.Items
arr2 = dict2.Items

GetCellDetails = Array(arr1, arr2)

End Function

Sub WriteCellDataToMemory(arr As Variant)

Dim arrSize As Long
arrSize = UBound(arr)
Range(Cells(1, 1), Cells(1 + arrSize, arrSize+1)) = Application.Transpose(arr)

End Sub

也许一个插图会帮助你理解

enter image description here

所以你有一个多维的 obj1objX
您将它们粘贴在将它们存储为对象的一维数组中

关于Excel VBA将数组数组传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19793033/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com