我正在使用mySql服务器连接将表数据导入excel。我总共有三个查询,其中两个工作正常,可以从copyFromRecordSet中正确复制。但是,当我使用copyFromRecordset时,第三个查询不能正常工作。它获得了我想要的两列,但省略了下五列。当我在数据库GUI中使用查询时,查询可以正常工作,所以这不是问题。
我正在尝试使用copyFromRecordSet的替代方法,这是我从https://support.microsoft.com/en-us/help/246335/how-to-transfer-data-from-an-ado-recordset-to-excel-with-automation更改的一段代码。
'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
这就是TransposeDim函数。
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
但是,当我运行这段代码时,查询再次省略了最后五列。
对于如何解决这段代码的任何见解或对为什么copyFromRecordSet表现异常的见解,将不胜感激。
最佳答案
为了正确访问某些记录,必须将recordSet的游标设置为客户端。我能够通过使用以下方法做到这一点:
在使用我的查询打开记录集之后,在我的代码中RS.CursorLocation = adUseClient
。然后,我只能使用CompareFile.Sheets("VendorFilteredPriceChangeReport").Range("A2").CopyFromRecordset RS
从记录集中复制数据,并且在工作簿中得到了正确的数据。