標籤:
VBA串連Oracle需要添加引用:
之後,連接字串為:Provider = MSDAORA.1;Password=******;User ID=XXXXXXX;Data Source=DBID;Persist Security Info=True
然後使用ado的標準封裝使用即可,1、使用ADO.CONNECTION,開啟串連,2、使用ADO.RECODESET查詢DB,使用connection.Excute執行更新刪除等操作。
具體代碼如下:
Public Sub ConOra()Dim sht As Worksheet Set sht = ActiveSheet On Error GoTo ErrMsg: ‘串連串 Dim ConnDB As ADODB.Connection Set ConnDB = New ADODB.Connection Dim ConnStr As String ‘ 結果集 Dim DBRst As ADODB.Recordset Set DBRst = New ADODB.Recordset ‘SQL文 Dim SQLRst As String Dim OraOpen As Boolean OraOpen = False ‘Oracle資料庫的相關配置 ConnStr = getConnStr() ‘ ConnDB.CursorLocation = adUseServer ConnDB.Open ConnStr ConnDB.Execute ("select * from dual") OraOpen = True ‘成功執行後,資料庫即被開啟 ‘MsgBox "Connect to the oracle database Successful!", vbInformation, "Connect Successful" ‘DBRst.ActiveConnection = ConnDB ‘DBRst.CursorLocation = adUseServer ‘DBRst.LockType = adLockBatchOptimistic SQLRst = "Select * From " & getTableName() & " where rownum = 1 " ‘DBRst.Open SQLRst, ConnDB, adOpenStatic, adLockBatchOptimistic DBRst.Open SQLRst, ConnDB
查詢之後,對於RecordSet 的使用:
1、擷取列名:
For i = 1 To DBRst.Fields.Count sht.Cells(2, i) = DBRst.Fields(i - 1).Name Next
2、擷取值:
Do Until DBRst.EOF For i = 1 To DBRst.Fields.Count sht.Cells(4, i) = DBRst.Fields(i - 1).Value Next i DBRst.MoveNext Loop
3、判斷RecordSet是否為空白:
If DBRst.BOF And DBRst.EOF Then MsgBox "資料庫中未查詢出任何資料,請將做成的資料寫入第4行!", vbInformation, "提示" End If
4、記得關閉串連喲。
5、如果按照以上方法,仍無無法串連DB,並提示:串連無法開啟,這是因為Office的安裝目錄中包含(86)導致的,重新按照OFFICE到其他非program檔案夾下即可解決。
ExcelVBA串連Oracle