excel - VBA 和 Oracle 数据库通用连接
问题描述
我正在尝试使用 vba 连接到 oracle 数据库,但无法使其正常工作。该代码与某种表格完美配合,但有些表格会给我一个错误13 type mismatch
,有时3021 bof or eof is true
不匹配开启:mtxData = Application.Transpose(rs.GetRows)
我不知道为什么会这样。另外我想说这是我第一次使用 oracle 和 vba。
到目前为止我的代码:
Sub Load_data()
Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
cn.Open ( _
"Provider=*****; User ID = ****; Password = ****; Data Source = *****")
Dim i As Long
For i = 1 To 20
Load_data_into_sheet Sheets("Sheet1"), "COLLABNAME" & i, cn
Next
cn.Close
End Sub
Private Sub Load_data_into_sheet(ws As Worksheet, CollabName As String, cn As ADODB.Connection)
ws.Select
Dim rs As ADODB.recordSet
Dim col As Integer
Dim row As Integer
Dim Query As String
Dim mtxData As Variant
Set rs = New ADODB.recordSet
rs.Open "select * from ZAR01", cn
With ws
col = 0
'First Row: names of columns
Do While col < rs.Fields.Count
.Cells(1, col + 1) = rs.Fields(col).Name
col = col + 1
Loop
mtxData = Application.Transpose(rs.GetRows)
.Range("A2").Resize(UBound(mtxData, 1) - LBound(mtxData, 1) + 1, UBound(mtxData, 2) - LBound(mtxData, 2) + 1) = mtxData
End With
rs.Close
'adOpenStatic, adLockReadOnly, adCmdText Or adAsyncExecute
End Sub
解决方案
我找到了解决方案。希望有人会发现它有用
Sub OracleLocalConnect()
Dim RecordSet As New ADODB.RecordSet
Dim con As New ADODB.Connection
Dim ExcelRange As Range
Dim SQLStr As String
Dim ws As Worksheet
con.ConnectionString = "Provider=****; User ID = ****; Password = ****; Data Source = ****"
con.Open
Set RecordSet = CreateObject("ADODB.Recordset")
SQLStr = "SELECT * FROM WIN1 WHERE (nvl(win1cmfg,' ') <> 'C' and nvl(win1scfg,' ') <> 'C' and win1rcls = '00' and win1rsts = '0' )"
RecordSet.Open SQLStr, con, adOpenStatic, adLockReadOnly
Set ws = ActiveWorkbook.Sheets("Sheet1")
Set ExcelRange = ws.Range("A2")
ExcelRange.CopyFromRecordset RecordSet
RecordSet.Close
con.Close
Exit Sub
End Sub
推荐阅读
- pandas - 如何获取一行中的最后一个可用值来填充 NaN 值
- html - 如何解码此文本并将其显示为阿拉伯语?
- c# - 我想在我的 Winform 应用程序中添加 Telerik Grid 但遇到运行时异常
- docker - 为什么我的服务在 docker swarm 中启动后没有出现在网络上?
- flutter - 颤振类型'列表
' 不是类型转换中类型 'String' 的子类型 - javascript - 在 Mutation Observer 中设置变量会导致 Mozilla 崩溃
- loops - For循环函数
- html - 如何仅使用 HTML 和 CSS 使我的响应式导航栏具有粘性?
- java - Gson 库无法像解析大型 JSON 文件那样可靠地工作
- html - 为使用 jQuery 创建的复选框元素设置处理程序的最佳方法