如何用vba编写一个抽取oracle数据库表数据,把表的表名,字段名,数据显示在一个新建的excel页中,要求需要:需要抽取的库名从excel的Sheet1中A1获取,数据库的账号在Sheet1中A2获取,数据库的密码在Sheet1中A3获取,要抽取数据的表名在Sheet1中A4获取,抽取数据的WHERE条件在Sheet1中A5获取,并且在Sheet1中A6的位置设计一个开始执行程序的按钮
时间: 2024-03-09 08:48:50 浏览: 71
以下是一个简单的VBA代码,可以实现你的需求:
```vba
Sub ExtractDataFromOracle()
Dim con As Object
Set con = CreateObject("ADODB.Connection")
'从Sheet1中获取参数
Dim dbName As String
dbName = Sheets("Sheet1").Range("A1").Value
Dim dbUser As String
dbUser = Sheets("Sheet1").Range("A2").Value
Dim dbPassword As String
dbPassword = Sheets("Sheet1").Range("A3").Value
Dim tableName As String
tableName = Sheets("Sheet1").Range("A4").Value
Dim whereClause As String
whereClause = Sheets("Sheet1").Range("A5").Value
'连接Oracle数据库
con.Open "Driver={Oracle in OraClient11g_home1};Dbq=" & dbName & ";Uid=" & dbUser & ";Pwd=" & dbPassword & ";"
'执行SQL查询
Dim rs As Object
Set rs = CreateObject("ADODB.Recordset")
rs.Open "SELECT * FROM " & tableName & " WHERE " & whereClause, con
'将结果写入新建的Excel页
Dim wb As Workbook
Set wb = Workbooks.Add
Dim ws As Worksheet
Set ws = wb.Sheets(1)
Dim i As Integer
For i = 0 To rs.Fields.Count - 1
ws.Cells(1, i + 1).Value = rs.Fields(i).Name
Next i
ws.Range("A2").CopyFromRecordset rs
'关闭连接
rs.Close
con.Close
End Sub
```
在Sheet1中添加一个按钮,然后将其绑定到这个VBA宏即可。
阅读全文
相关推荐















