Search code examples
vbaexceladodb

CopyFromRecordset copies & pastes only first one row even though multiple records are present in Excel


I have an Excel sheet containing table like data

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

Results :
Only first row and other records are ignored.

I have tried below query .,

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

Which gives 5 as result.

Please let me know why other records not copied into recordset?


Solution

  • Here's a subroutine that successfully pastes a recordset.

    Note that the range it pastes to is the same size of the recordset via the intMaxRow and intMaxCol variables:

    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
    

    Using that example as a model, I'd try somehting like this for your code:

    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