vba - 将多维数组传递到 VBA 中的记录集变量中
问题描述
我有一个数组,我想用它作为我的数据源来构建数据透视表,我知道数据透视表不会接受数组,我应该使用记录集作为数据透视表会接受这个。
我正在努力使用我的数组构建记录集。
如何将多维数组传递到记录集中?
或者
如何在数据透视表中使用我的数组数据?
谢谢你的帮助。
解决方案
您正在寻找的术语是“断开连接的记录集”。一旦你知道谷歌的话,就会有很多例子。例如:https ://developer.rhino3d.com/guides/rhinoscript/disconnected-recordset-sorting/
这是一个基本示例:
Sub PopCache()
Dim pc As PivotCache, rs As ADODB.Recordset, pt As PivotTable
Dim arr, x As Long
Set pc = ThisWorkbook.PivotCaches.Create(xlExternal)
'get an array for testing
arr = ActiveSheet.Range("J4").CurrentRegion.Value
'populate the pivotcache from a recordset
Set pc.Recordset = ArrayToRecordSet(arr, _
Array("Name", "Color", "Length"))
Set pt = pc.CreatePivotTable(ActiveSheet.Range("B2"))
End Sub
'Take an array of data and an array of field names and
' return a populated disconnected recordset
Function ArrayToRecordSet(arr, fieldNames) As Object
Dim rs As Object, r As Long, c As Long, h, f As Long
Set rs = CreateObject("ADODB.Recordset")
For Each h In fieldNames
rs.Fields.Append h, adVariant
Next h
rs.Open
For r = LBound(arr, 1) To UBound(arr, 1)
rs.AddNew
f = 0
For c = LBound(arr, 2) To UBound(arr, 2)
rs.Fields(f).Value = arr(r, c)
f = f + 1
Next c
Next r
Set ArrayToRecordSet = rs
End Function
推荐阅读
- python - 如何使用 FOR 循环在 python 中以递增的价格向币安发送多个订单
- python - 我怎么知道它是否在python的列表中有列表
- r - 使用 glmer 的模型收敛问题
- mysql - MariaDB max_open_files 超过 600k
- c# - 如何将 WPF 网格单元格复制到同一网格中的另一个单元格
- c++ - 为什么从 Swift (Xcode) 调用时 fstream 不起作用?
- visual-studio-code - 如何扩展 VSCode 的交互式终端的文本字体
- javascript - 如何在新的小 div 中打开 window.open 而不是全屏?
- swift - 如何在 MacOS 的 SwiftUI 中创建多行文本字段?
- c - C中的字符串向量打印错误的字符串