VBA部分二维数组转换为combobox.List

时间:2016-10-21 08:11:13

标签: arrays excel vba excel-vba combobox

在我的代码中,我通过SQL查询得到Variant queryResult内的二维数组。

queryResult = RetrieveRecordset("SELECT * FROM Materials;")
然后

数组看起来像:

enter image description here

如果我试图填满Combobox

cbSTPScrewedMaterial.List = queryResult

它仅填充值1和塑料,但我希望获得从塑料到硬塑料的值 - > queryResult(1)在上面的图片上,但是当我输入

cbSTPScrewedMaterial.List = queryResult(1)

VBA回应我运行时错误9:下标超出范围。 你有想法,我做错了什么以及如何解决它?

1 个答案:

答案 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)