在我的代码中,我通过SQL查询得到Variant queryResult内的二维数组。
queryResult = RetrieveRecordset("SELECT * FROM Materials;")
然后数组看起来像:
如果我试图填满Combobox
cbSTPScrewedMaterial.List = queryResult
它仅填充值1和塑料,但我希望获得从塑料到硬塑料的值 - > queryResult(1)在上面的图片上,但是当我输入
时cbSTPScrewedMaterial.List = queryResult(1)
VBA回应我运行时错误9:下标超出范围。 你有想法,我做错了什么以及如何解决它?
答案 0 :(得分:1)
queryResult
是一个包含2行和5列的二维数组
将您的组合框ColumnCount
属性设置为5
cbSTPScrewedMaterial.ColumnCount = 5
并将它们全部展示
此外queryResult(1)
试图将二维数组作为一维数组进行访问,从而导致错误
你可以使用一个函数从一个给定的二维数组行中返回一维数组,如下所示
Option Explicit
Function GetQueryRow(arr As Variant, iRow As Long) As Variant
Dim j As Long
ReDim arrRow(LBound(arr, 2) To UBound(arr, 2)) As Variant
For j = LBound(arr, 2) To UBound(arr, 2)
arrRow(j) = arr(iRow, j)
Next j
GetQueryRow = arrRow
End Function
用作:
Dim queryResult As Variant
Dim queryRow As Variant
queryResult = RetrieveRecordset("SELECT * FROM Materials;")
queryRow = GetQueryRow(queryResult, 1)
或“直接”
Dim queryRow As Variant
queryRow = GetQueryRow(RetrieveRecordset("SELECT * FROM Materials;"), 1)
甚至“更直接”
MsgBox GetQueryRow(RetrieveRecordset("SELECT * FROM Materials;"), 1)(1)