ExcelVBA串連Oracle

來源:互聯網
上載者:User

標籤:

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.