简体   繁体   English

使用 Excel VBA 从 Oracle 表中检索数据到 Excel

[英]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.我编写了代码来从 Oracle DB 中的表中获取数据并使用 VBA 转储到 Excel 工作表。

In Excel, it displays the first row repeatedly.在 Excel 中,它重复显示第一行。 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.例如,如果从 DB 返回了 45 个不同的行,则在 Excel 工作表中,所有 45 行都与 DB 中的第一行相同。

How to get the rows from the DB to Excel?如何将行从数据库获取到 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
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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM