1

我编写了代码来从 Oracle DB 中的表中获取数据并使用 VBA 转储到 Excel 表中。

在 Excel 中,它重复显示第一行。例如,如果从数据库返回 45 行不同的行,则在 Excel 工作表中,所有 45 行都与数据库中的第一行相同。

如何将行从 DB 获取到 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
4

1 回答 1

0
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
于 2016-03-09T09:54:04.717 回答