Archiviazione del recordset nell'array in VBA

Oct 18 2020

Ho una funzione dinamica per chiamare una stored procedure e memorizzare il recordset in un array, che voglio usare in un altro sub. Ma non ottengo il risultato in una matrice come questa:

Array(0,0) = 1
Array(0,1) = Miller
Array(1,0) = 2
Array(1,1) = Jones
Array(2,0) = 3
Array(2,1) = Jackson
....

Il risultato di My Array è così:

Array(0,0) = 1
Array(1,0) = Miller
Array(0,1) = 2
Array(1,1) = Jones
Array(0,2) = 3
Array(1,2) = Jackson
....

Per capire il processo ti sto mostrando SQL-statement:

CREATE PROCEDURE dbo.sp_GetAllPersons
AS
BEGIN
    SET NOCOUNT ON;

    SELECT DISTINCT u.ID, u.Name
    FROM dbo.v_Users u
END
GO

La funzione per ottenere il recordset e memorizzarlo in un array:

Public Function fGetDataBySProc(ByVal sProcName As String) As Variant
    ...
    
    Dim Cmd As New ADODB.Command
    With Cmd
        .ActiveConnection = cn
        .CommandText = sProcName
        .CommandType = adCmdStoredProc
    End With
    
    Dim ObjRs As New ADODB.Recordset: Set ObjRs = Cmd.Execute
    Dim ArrData() As Variant
    
    If Not ObjRs.EOF Then
        ArrData = ObjRs.GetRows(ObjRs.RecordCount)
    End If
    
    ObjRs.Close
    cn.Close
    
    fGetDataBySProc = ArrData
End Function

Il sottotitolo in cui viene chiamata la funzione:

Public Sub cbFillPersons()
    Dim sProcString As String: sProcString = "dbo.sp_GetAllPersons"
    Dim ArrData As Variant: ArrData = fGetDataBySProc(sProcString)   
    Dim i as Integer
    
    ' Just for testing
    For i = LBound(ArrData) To UBound(ArrData)
        Debug.Print "AddItem: " & ArrData(0, i)
        Debug.Print "List: " & ArrData(1, i)
    Next
End Sub

Non so cosa sto sbagliando. Forse è il .GetRows()metodo?

Risposte

2 VBasic2008 Oct 18 2020 at 22:27

Trasponi array 2D

  • Puoi trasporre l'array risultante usando la getTransposedArrayfunzione.

  • Quindi l'ultima riga nella tua fGetDataBySProcfunzione sarebbe:

     fGetDataBySProc = getTransposedArray(ArrData) 
    

La funzione

Function getTransposedArray(Data As Variant) _
         As Variant
    
    Dim LB2 As Long
    LB2 = LBound(Data, 2)
    Dim UB2 As Long
    UB2 = UBound(Data, 2)
    
    Dim Result As Variant
    ReDim Result(LB2 To UB2, LBound(Data, 1) To UBound(Data, 1))
    
    Dim i As Long
    Dim j As Long
    
    For i = LBound(Data, 1) To UBound(Data, 1)
        For j = LB2 To UB2
            Result(j, i) = Data(i, j)
        Next j
    Next i
    
    getTransposedArray = Result
                 
End Function