我使用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为何会表现奇怪的见解,将不胜感激
答案 0 :(得分:0)
为了正确访问某些记录,必须将recordSet的光标设置为客户端。我能够通过使用:
我的代码中的RS.CursorLocation = adUseClient
,在使用我的查询打开记录集之后。然后,我只能使用CompareFile.Sheets("VendorFilteredPriceChangeReport").Range("A2").CopyFromRecordset RS
从记录集中复制数据,我在工作簿中获得了正确的数据。