Speichern von Recordset in Array in VBA
Oct 18 2020
Ich habe eine dynamische Funktion, um eine gespeicherte Prozedur aufzurufen und das Recordset in einem Array zu speichern, das ich in einem anderen Sub verwenden möchte. Aber ich bekomme das Ergebnis in einem Array wie diesem nicht:
Array(0,0) = 1
Array(0,1) = Miller
Array(1,0) = 2
Array(1,1) = Jones
Array(2,0) = 3
Array(2,1) = Jackson
....
Mein Array-Ergebnis sieht folgendermaßen aus:
Array(0,0) = 1
Array(1,0) = Miller
Array(0,1) = 2
Array(1,1) = Jones
Array(0,2) = 3
Array(1,2) = Jackson
....
Um den Prozess zu verstehen, zeige ich Ihnen Folgendes 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
Die Funktion zum Abrufen und Speichern des Recordset in einem 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
Das Sub, in dem die Funktion aufgerufen wird:
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
Ich weiß nicht, was ich falsch mache. Vielleicht ist es die .GetRows()Methode?
Antworten
2 VBasic2008 Oct 18 2020 at 22:27
2D-Array transponieren
Sie können Ihr resultierendes Array mit der
getTransposedArrayFunktion transponieren .Dann wäre die letzte Zeile in Ihrer
fGetDataBySProcFunktion:fGetDataBySProc = getTransposedArray(ArrData)
Die Funktion
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