vba数组放oracle查询的数据
时间: 2023-12-10 14:04:21 浏览: 87
VBA 操作Oracle数据库
可以使用ADO(ActiveX Data Objects)来连接Oracle数据库并执行查询,将查询结果存储在VBA数组中。以下是一个简单的示例代码:
```
Sub QueryOracle()
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim arrData() As Variant
Dim i As Long, j As Long
Set conn = New ADODB.Connection
'连接Oracle数据库
conn.ConnectionString = "Provider=OraOLEDB.Oracle;Data Source=YourDataSource;User ID=YourUserID;Password=YourPassword;"
conn.Open
'执行查询
Set rs = conn.Execute("SELECT * FROM YourTable")
'将查询结果存储在数组中
If Not rs.EOF Then
rs.MoveLast
rs.MoveFirst
arrData = rs.GetRows(rs.RecordCount)
End If
'关闭连接
rs.Close
Set rs = Nothing
conn.Close
Set conn = Nothing
'将数组中的数据输出到Excel工作表
For i = LBound(arrData, 2) To UBound(arrData, 2)
For j = LBound(arrData, 1) To UBound(arrData, 1)
Cells(j + 1, i + 1).Value = arrData(j, i)
Next j
Next i
End Sub
```
在此示例中,我们使用了ADODB.Connection和ADODB.Recordset对象来连接Oracle数据库并执行查询。查询结果存储在名为arrData的VBA数组中,然后输出到Excel工作表中。请注意,在连接Oracle数据库时,需要更改连接字符串中的数据源、用户名和密码以匹配您的环境。
阅读全文