程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 數據庫知識 >> Oracle數據庫 >> 關於Oracle數據庫 >> Excel VBA連接並操作Oracle

Excel VBA連接並操作Oracle

編輯:關於Oracle數據庫
以下是通過Excel 的VBA連接Oracle並操作Oracle相關數據的示例
Excel 通過VBA連接數據庫需要安裝相應的Oracle客戶端工具並引用ADO的相關組件,引用ADO相關組件可按如下步驟操作:
  1、打開VBA編輯器,在菜單中點選“工具”,“引用”;
  2、確保“Microsoft ActiviteX Data Objects 2.8 Library”和“Microsoft ActiviteX Data ObjectS Recordset 2.8 Library”被勾選上。
  建立連接過程,代碼如下:
代碼如下:

Public Sub ConOra()
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
Dim SQLRst As String
Dim OraOpen As Boolean
OraOpen = False
OraID="Orcl" 'Oracle數據庫的相關配置
OraUsr="user"
OraPwd="password"
ConnStr = "Provider = MSDAORA.1;Password=" & OraPwd & _
";User ID=" & OraUsr & _
";Data Source=" & OraID & _
";Persist Security Info=True"
ConnDB.CursorLocation = adUseServer
ConnDB.Open ConnStr
OraOpen = True '成功執行後,數據庫即被打開
'MsgBox "Connect to the oracle database Successful!", vbInformation, "Connect Successful"
DBRst.ActiveConnection = ConnDB
DBRst.CursorLocation = adUseServer
DBRst.LockType = adLockBatchOptimistic
SQLRst = "Select * From TstTab"
DBRst.Open SQLRst, ConnDB, adOpenStatic, adLockBatchOptimistic
DBRst.MoveFirst
Exit Function
ErrMsg:
OraOpen = False
MsgBox "Connect to the oracle database fail ,please check!", vbCritical, "Connect fail!"
End Function
Public Sub ConOra()
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
Dim SQLRst As String
Dim OraOpen As Boolean
OraOpen = False
OraID="Orcl" 'Oracle數據庫的相關配置
OraUsr="user"
OraPwd="password"
ConnStr = "Provider = MSDAORA.1;Password=" & OraPwd & _
";User ID=" & OraUsr & _
";Data Source=" & OraID & _
";Persist Security Info=True"
ConnDB.CursorLocation = adUseServer
ConnDB.Open ConnStr
OraOpen = True '成功執行後,數據庫即被打開
'MsgBox "Connect to the oracle database Successful!", vbInformation, "Connect Successful"
DBRst.ActiveConnection = ConnDB
DBRst.CursorLocation = adUseServer
DBRst.LockType = adLockBatchOptimistic
SQLRst = "Select * From TstTab"
DBRst.Open SQLRst, ConnDB, adOpenStatic, adLockBatchOptimistic
DBRst.MoveFirst
Exit Function
ErrMsg:
OraOpen = False
MsgBox "Connect to the oracle database fail ,please check!", vbCritical, "Connect fail!"
End Function

可以根據需要調整SQL語句,獲取相關數據,並輸出到Excel完成數據處理
上述代碼在Windows XP SP3/2003 SP2 + Office2003下測試通過.
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved