即使Excel中存在多个logging,CopyFromRecordset也只复制并粘贴第一行

我有一个Excel工作表,包含像数据表

strSQL = "SELECT S.FIELD_NAME1,S.FIELD_NAME2,S.FIELD_NAME3 from [SourceData$A1:IV6] S" Dim cn as ADODB.Connection Dim rs as ADODB.Recordset cn.Open strCon Set rs = CmdSqlData.Execute() Worksheets("SourceData").Cells.ClearContent Worksheets("AnswerData").Cells(2, 1).CopyFromRecordset rs 

结果:
只有第一行和其他logging被忽略。

我已经试过下面的查询。

 strSQL = "SELECT COUNT(*) from [SourceData$A1:IV6] S" 

结果是5

请让我知道为什么其他logging不复制到logging集?

这是一个成功粘贴logging集的子例程。

请注意,它通过intMaxRow和intMaxColvariables粘贴的范围与logging集的大小相同:

 Sub sCopyFromRS() 'Send records to the first 'sheet in a new workbook ' Dim rs As Recordset Dim intMaxCol As Integer Dim intMaxRow As Integer Dim objXL As Excel.Application Dim objWkb As Workbook Dim objSht As Worksheet Set rs = CurrentDb.OpenRecordset("Customers", _ dbOpenSnapshot) intMaxCol = rs.Fields.Count If rs.RecordCount > 0 Then rs.MoveLast: rs.MoveFirst intMaxRow = rs.RecordCount Set objXL = New Excel.Application With objXL .Visible = True Set objWkb = .Workbooks.Add Set objSht = objWkb.Worksheets(1) With objSht .Range(.Cells(1, 1), .Cells(intMaxRow, _ intMaxCol)).CopyFromRecordset rs End With End With End If End Sub 

使用这个例子作为模型,我会尝试这样的代码:

 strSQL = "SELECT S.FIELD_NAME1,S.FIELD_NAME2,S.FIELD_NAME3 from [SourceData$A1:IV6] S" Dim cn as ADODB.Connection Dim rs as ADODB.Recordset Dim intMaxCol as Integer Dim intMaxRow as Integer cn.Open strCon Set rs = CmdSqlData.Execute() intMaxCol = rs.Fields.Count '- MoveLast/First to get an accurate RecordCount rs.MoveLast rs.MoveFirst If rs.RecordCount > 0 then '-thought you could put the MoveLast/First here but maybe not. intMaxRow = rs.RecordCount With Worksheets("AnswerData") .Range(.Cells(2,1),.Cells(intMaxRow+1,intMaxColumn)).CopyFromRecordset rs End With End If 

这个答案取决于您在Excel中提供的ODBC数据库驱动程序。

由于我的公司env,我不得不使用一个非常古老的Oracle ODBC驱动程序。 在我的情况下, Recordset.RecordCount始终是-1 。 默认情况下,不支持Recordset.MoveLastRecordset.MoveFirst 。 像原来的问题一样,调用Excel.Range.CopyFromRecordset(Recordset)也只写一行。

您可能需要不同地configuration您的ADODB.Recordset 。 试试这个代码:

 Dim dbConn As ADODB.Connection Dim rs As ADODB.Recordset Dim rng As Excel.Range Dim rowCount As Long ' TODO: Init your dbConn here. ' TODO: Init your rng here. Set rs = New ADODB.Recordset ' http://www.w3schools.com/ado/prop_rs_cursortype.asp rs.CursorType = ADODB.CursorTypeEnum.adOpenKeyset rs.Open sql, dbConn rowCount = rng.CopyFromRecordset(rs) 

对于我的驱动程序,这解决了这个问题。 但是,你的里程可能会有所不同

您可以在这里阅读有关ADO游标types的更多信息 。