1

我正在使用 VBA 查询 MySQL 数据库。这涉及使用我已经启动并运行良好的 ODBC 驱动程序。

我想在 VBA 多维数组中返回我的查询结果。(字段为列,记录为行)

VBA 中的 ODBC MySQL 驱动程序存在一个已知问题,即该属性的.RecordCount计算结果为 -1,而不是成功时的实际记录数。.EOF这意味着在循环提取记录之前,我不能使用它来调整数组的大小。

我试过这个:

If Rs.RecordCount <> 0 Then //Just check if it's not false as recordcount is not fully functional
        Fields = Rs.Fields.Count //This actually works
        rw = 1
        Dim result()
        Do Until Rs.EOF
            ReDim Preserve result(1 To rw, 1 To Fields)
            C = 1
            For Each MyField In Rs.Fields
                result(rw, C) = MyField
                C = C + 1
            Next MyField
            Rs.MoveNext
            rw = rw + 1
        Loop
        get_result = result //Output the result
End if

但我收到错误 9:下标超出范围。这让我发疯,在 php 中这将是微不足道的,但由于某种原因,我无法在 VBA 中解决这个问题。有任何想法吗?

4

2 回答 2

1

好的,哇,看来我需要做的就是使用.getRows

所以我的代码变成:

If Rs.RecordCount <> 0 Then 
        get_result = Rs.getRows 
End if
于 2013-10-01T09:32:14.367 回答
1

我需要一种方法来用我的数据返回标题字段,因为Rs.GetRows只包含行数据。我创建了一个函数来帮助解决这个问题,并认为将它添加到这个旧帖子中会很有帮助,以防其他人有同样的需求。

'RETURNS A TWO-DIM ARRAY FROM A RECORDSET WITH OPTION TO INCLUDE HEADERS
Public Function ArrayFromRecordset(ByVal Rs As Object, Optional ByVal IncludeHeaders As Boolean = True) As Variant

    '@author Robert Todar <robert@roberttodar.com>

    'CHECK TO MAKE SURE THERE ARE RECORDS TO PULL FROM
    If Rs.BOF Or Rs.EOF Then
        Exit Function
    End If

    'SIMPLY RETURN DATA IF HEADERS NOT INCLUDED
    If IncludeHeaders = False Then
        ArrayFromRecordset = Rs.getrows
        Exit Function
    End If

    'STORE RS DATA IN VARIABLE
    Dim RsData As Variant
    RsData = Rs.getrows

    'TEMP ARRAY WILL USE THIS TO ACCOUNT FOR THE HEADING ROW
    Const HeadingIncrement As Integer = 1

    'REDIM TEMP TO ALLOW FOR HEADINGS AS WELL AS DATA
    Dim Temp As Variant
    ReDim Temp(LBound(RsData, 2) To UBound(RsData, 2) + HeadingIncrement, LBound(RsData, 1) To UBound(RsData, 1))

    'ADD HEADERS TO ARRAY
    Dim HeaderIndex As Long
    For HeaderIndex = 0 To Rs.Fields.Count - 1
        Temp(LBound(Temp, 1), HeaderIndex) = Rs.Fields(HeaderIndex).Name
    Next HeaderIndex

    'ADD DATA TO ARRAY
    Dim RowIndex As Long
    For RowIndex = LBound(Temp, 1) + HeadingIncrement To UBound(Temp, 1)

        Dim ColIndex As Long
        For ColIndex = LBound(Temp, 2) To UBound(Temp, 2)
            Temp(RowIndex, ColIndex) = RsData(ColIndex, RowIndex - HeadingIncrement)
        Next ColIndex

    Next RowIndex

    'RETURN
    ArrayFromRecordset = Temp

End Function
于 2019-05-09T17:04:44.837 回答