首页 > 解决方案 > 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.

我怎样才能快速正确地做到这一点?

标签: sqlexcelvbaadodb

解决方案


通常,一个记录集只能从头到尾读取一次(嗯,有一些方法可以打开一个记录集,以便以任何顺序访问记录,但通常这不是必需的,也不是所有数据都支持来源)。

从记录集中获取数据的最简单方法是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

推荐阅读