Ich verwende eine mySql-Serververbindung, um Tabellendaten in Excel zu erhalten. Ich habe insgesamt drei Abfragen, von denen zwei perfekt funktionieren und korrekt aus copyFromRecordSet kopiert werden. Die dritte Abfrage funktioniert jedoch nicht ordnungsgemäß, wenn ich copyFromRecordset verwende. Es bekommt zwei der Spalten, die ich will, aber die nächsten fünf weglässt. Die Abfrage funktioniert ordnungsgemäß, wenn ich sie in einer Datenbank-GUI verwende, so dass das nicht das Problem ist.Fehler beim Abrufen der Tabelle aus dem VBA-Recordset
Ich versuche, eine Alternative zu copyFromRecordSet zu verwenden, ein Stück Code, den ich von https://support.microsoft.com/en-us/help/246335/how-to-transfer-data-from-an-ado-recordset-to-excel-with-automation geändert habe.
'Open and copy the recordset to an array to allow for copying into worksheet
RS.Open PriceChangeQuery
recArray = RS.GetRows
recCount = UBound(recArray, 2) + 1 '+1 since the array is zero-based
fldCount = RS.Fields.Count
' Check the array for contents that are not valid when
' copying the array to an Excel worksheet
For iCol = 0 To fldCount - 1
For iRow = 0 To recCount - 1
' Take care of Date fields
If IsDate(recArray(iCol, iRow)) Then
recArray(iCol, iRow) = Format(recArray(iCol, iRow))
' Take care of OLE object fields or array fields
ElseIf IsArray(recArray(iCol, iRow)) Then
recArray(iCol, iRow) = "Array Field"
End If
Next iRow 'next record
Next iCol 'next field
'Transpose and copy the array to the worksheet,
'starting in cell A2
CompareFile.Sheets("VendorFilteredPriceChangeReport").Cells(2, 1).Resize(recCount, fldCount).Value = TransposeDim(recArray)
'CompareFile.Sheets("VendorFilteredPriceChangeReport").Range("A2").CopyFromRecordset RS
'Close ADO objects
RS.Close
Und das ist die TransposeDim-Funktion.
Function TransposeDim(v As Variant) As Variant
' Custom Function to Transpose a 0-based array (v)
Dim X As Long, Y As Long, Xupper As Long, Yupper As Long
Dim tempArray As Variant
Xupper = UBound(v, 2)
Yupper = UBound(v, 1)
ReDim tempArray(Xupper, Yupper)
For X = 0 To Xupper
For Y = 0 To Yupper
tempArray(X, Y) = v(Y, X)
Next Y
Next X
TransposeDim = tempArray
End Function
Allerdings, wenn ich dieses Stück Code ausführen die Abfrage erneut die letzten fünf Spalten Weglassen.
Keine Erkenntnisse darüber, wie dieses Stück Code oder Einsichten zu beheben, warum CopyFromRecordset seltsam
Zuerst, anstatt TransposeDim aufrufen, warum nicht die Elemente im Array korrekt in der Schleife speichern? Ändere einfach '' 'recArray (iCol, iRow) = Format (recArray (iCol, iRow))' '' '' '' 'recArray (iRow, iCol) = Formatiere (recArray (iRow, iCol))' '' und beliebig Weitere Referenzen. –
Danke! Ich werde das tun –
Stellt sich heraus, ich habe nicht FldCount auf einen Wert gesetzt - das Stück Code funktioniert jetzt, nur den gleichen Fehler wie CopyFromRecordset –