如何将 Select 查询和获取详细信息写入 Excel |VBA|

How to Write Select Query and Fetch Details to Excel |VBA|

我有一个查询需要添加 查询语句 并将详细信息提取到 Excel Sheet

Table 名字是: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

这应该可以正常工作 摘自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