'Retrieving data from Oracle table to Excel using Excel VBA

I have written code to get data from a table in Oracle DB and dump to an Excel sheet using VBA.

In Excel, it displays the first row repeatedly. For an instance, if there are 45 different rows returned from the DB, in the Excel sheet all 45 rows are the same as the first row in the DB.

How to get the rows from the DB to Excel?

Sub Results()

    Dim SQL As String
    Dim OraDynaSet As Object
    Dim i As Integer

    SQL = "Select * from Employee where EmpID=20"
    Set OraDynaSet = objDataBase.DBCreateDynaset(SQL, 0&)

    If OraDynaSet.RecordCount > 0 Then

        'There were records retrieved

        OraDynaSet.MoveFirst

        For ICOLS = 0 To OraDynaSet.Fields.Count - 1
            .Cells(1, ICOLS + 1).Value = OraDynaSet.Fields(ICOLS).Name
        Next ICOLS

        'Loop the recordset for returned rows
        For i = 0 To OraDynaSet.RecordCount - 1

            For j = 0 To ICOLS - 1
                .Cells(2 + i, j + 1) = OraDynaSet.Fields(j).Value 
            Next j
        Next i

    Else
        MsgBox "No Matching records found"
    End If
End Sub


Solution 1:[1]

Dim SQL As String
Dim OraDynaSet As Object
Dim i As Integer

SQL = "Select * from Employee where EmpID=20"
Set OraDynaSet = objDataBase.DBCreateDynaset(SQL, 0&)

 If OraDynaSet.RecordCount > 0 Then
'There were records retrieved

     OraDynaSet.MoveFirst


     For ICOLS = 0 To OraDynaSet.Fields.Count - 1
       .Cells(1, ICOLS + 1).Value = OraDynaSet.Fields(ICOLS).Name
     Next ICOLS


    'Loop the recordset for returned rows
    For i = 0 To OraDynaSet.RecordCount - 1

      For j = 0 To ICOLS - 1
        .Cells(2 + i, j + 1) = OraDynaSet.Fields(j).Value

        Next j
        OraDynaSet.Movenext
    Next i


Else
    MsgBox "No Matching records found"
End If
End Sub

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 IAmAnonymous