【问题标题】:How to Write Select Query and Fetch Details to Excel |VBA|如何将选择查询和获取详细信息写入 Excel |VBA|
【发布时间】:2019-08-16 06:50:01
【问题描述】:

我有一个查询,我需要在其中添加 查询语句 并将该详细信息提取到 Excel 工作表中

表格名称是:Student_Details

ID|Name|Course|
1 |vik |MBA   |
2 |sik |CA    |
3 |mil |CP    |
4 |hil |MP    |

query : Select * from Student_Details;

如何在下面的查询中实现

Sub Ora_Connection()

Dim con As ADODB.Connection
Dim rs As ADODB.Recordset
Dim query As String

Set con = New ADODB.Connection
Set rs = New ADODB.Recordset

'---  Replace below highlighted names with the corresponding values

strCon = "Driver={Microsoft ODBC for Oracle}; " & _
"CONNECTSTRING=(DESCRIPTION=" & _
"(ADDRESS=(PROTOCOL=TCP)" & _
"(HOST=ora130b-example.intra)(PORT=1534))" & _
"(CONNECT_DATA=(SERVICE_NAME=JFG))); uid=jfg_o; pwd=ure;"
'---  Open the above connection string.

con.Open (strCon)
'---  Now connection is open and you can use queries to execute them.
'---  It will be open till you close the connection

con.Close

End Sub

【问题讨论】:

    标签: excel vba adodb


    【解决方案1】:

    这应该可以正常工作取自Link

    步骤:

    • 设置结果并执行查询
    • 循环打印这些结果。

    con.Open (strCon)
    
    query = "Select * from Student_Details"
    Set rs = con.Execute(query)
    
    Do While Not rs.EOF
      For i = 0 To rs.Fields.Count - 1
        Debug.Print rs.Fields(i).Name, rs.Fields(i).Value
      Next
      rs.MoveNext
    Loop
    rs.Close
    
    
    con.Close
    

    直接将数据复制到 Activesheet 使用:

    ActiveSheet.Range("A1").CopyFromRecordset rs
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多