以下是通過Excel 的VBA連接Oracle并操作Oracle相關(guān)數(shù)據(jù)的示例
Excel 通過VBA連接數(shù)據(jù)庫需要安裝相應(yīng)的Oracle客戶端工具并引用ADO的相關(guān)組件,引用ADO相關(guān)組件可按如下步驟操作:
1、打開VBA編輯器,在菜單中點(diǎn)選“工具”,“引用”;
2、確?!癕icrosoft ActiviteX Data Objects 2.8 Library”和“Microsoft ActiviteX Data ObjectS Recordset 2.8 Library”被勾選上。
建立連接過程,代碼如下:
復(fù)制代碼 代碼如下:
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數(shù)據(jù)庫的相關(guān)配置
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 '成功執(zhí)行后,數(shù)據(jù)庫即被打開
'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數(shù)據(jù)庫的相關(guān)配置
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 '成功執(zhí)行后,數(shù)據(jù)庫即被打開
'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
可以根據(jù)需要調(diào)整SQL語句,獲取相關(guān)數(shù)據(jù),并輸出到Excel完成數(shù)據(jù)處理
上述代碼在Windows XP SP3/2003 SP2 + Office2003下測試通過.
您可能感興趣的文章:- VBA中操作Excel常用方法總結(jié)
- excel vba 高亮顯示當(dāng)前行代碼
- excel vba 限制工作表的滾動(dòng)區(qū)域代碼
- 合并Excel工作薄中成績表的VBA代碼,非常適合教育一線的朋友
- 用vba實(shí)現(xiàn)將記錄集輸出到Excel模板
- Python + selenium + requests實(shí)現(xiàn)12306全自動(dòng)搶票及驗(yàn)證碼破解加自動(dòng)點(diǎn)擊功能
- python requests包的request()函數(shù)中的參數(shù)-params和data的區(qū)別介紹
- python:解析requests返回的response(json格式)說明
- 基于python requests selenium爬取excel vba過程解析