sql - Excel VBA Sql:ADODB.Recordset - GetRows(index) 列模拟
问题描述
我是 VBA Sql 的新手,我写了一个 SQL 查询并得到 ADODB.Recordset 作为结果。
我可以通过索引获取行值:
Dim rst As New ADODB.Recordset
Set rst.ActiveConnection = cn
rst.Open cmd
Dim myValues As Variant
myValues = rst.GetRows(1)
有没有按名称或索引获取列值的方法?
在我的任务中,我首先需要知道记录集中的行数,然后创建一个MyArr
具有此大小的数组,遍历列中的行columnname
(或使用索引indexname
),使用记录集列中的值计算一些值,然后将计算结果写入MyArr
.
我怎样才能快速正确地做到这一点?
解决方案
通常,一个记录集只能从头到尾读取一次(嗯,有一些方法可以打开一个记录集,以便以任何顺序访问记录,但通常这不是必需的,也不是所有数据都支持来源)。
从记录集中获取数据的最简单方法是GetRows
不带参数使用,它将返回所有行和列的值并将它们放入二维数组中。您只需要知道数组的第一个索引是列索引,第二个索引是行索引。请注意,两个维度的下限索引均为 0。
Dim myValues
myValues = rst.GetRows ' Read all data into 2-dimensional array
Debug.Print "# Cols: " & LBound(myValues, 1) & " to " & UBound(myValues, 1)
Debug.Print "# Rows: " & LBound(myValues, 2) & " to " & UBound(myValues, 2)
Dim myArr()
ReDim myArr(0 To UBound(myValues, 2))
Dim row As Long
For row = 0 To UBound(myValues, 2)
' myArr(row) = MagicCalculation(myValues(0, row), myValues(1, row), myValues(2, row))
Next row
' to list all field names:
Dim col As Long
For col = 0 To UBound(myValues, 1)
Debug.Print col & ". field: " & rs.Fields(col)
Next col
推荐阅读
- java - 如何通过 nginx 反向代理调试远程 Java 应用程序
- node.js - How to handle options object sent by dc.beginDialog to other component dialog
- python - Trouble scraping a website link using requests
- performance - Entity Framework Core - 来自其他数据库的 Upsert 实体遇到跟踪问题
- python - Conditional renaming of multiple files from multiple subfolders based on a list of prefix
- javascript - How to not import Vue in main js and store
- mongodb - 查找管道:`$match` 本地字段 `$in` 数组当 from value 是数组并且要找到本地值时
- c# - Azure 应用注册 - C# 应用的 SQL Server 权限
- excel - Altering values as a percentage to work with a graph
- android - 自定义语言字符串 Moodle Mobile