以下範例是根據我平時的環境 (DB, ODBC), 如果各位使用有何問題, 歡迎提出討論
'ADO - Query Oracle from Excel via ODBC driver
Sub ADO_example()
Dim con As Object, com As Object, rec As Object
Set con = CreateObject("ADODB.Connection")
Set com = CreateObject("ADODB.Command")
Set rec = CreateObject("ADODB.Recordset")
On Error GoTo ADO_Err
'星號部分依實際設定自行修改
con.Open "DRIVER={Microsoft ODBC for Oracle};UID=***WD=***;SERVER=*****;"
With com
.ActiveConnection = con
.CommandType = 1 '1=adCmdText 4=adCmdStoredProc
.CommandText = "select emp_no,emp_name from employee where dept_no='001'"
End With
Set rec = com.Execute
'整個複製到工作表
Cells(1, 1).CopyFromRecordset rec
'讀取欄名方式一
For Each f In rec.Fields
Debug.Print f.Name
Next
'讀取欄名方式二 PS. rec(0)為 rec.Fields(0) 之簡化寫法
Debug.Print rec(0).Name & ", " & rec(1).Name
'直接讀取Recordset資料
While Not rec.EOF 'Loop: 適用多筆
Debug.Print rec(0) & ", " & rec(1)
rec.MoveNext
Wend
rec.Close: con.Close
1 Set con = Nothing: Set com = Nothing: Set rec = Nothing
Exit Sub
ADO_Err:
MsgBox Err & vbLf & Err.Description, 16
GoTo 1
End Sub