【发布时间】:2016-01-07 19:55:29
【问题描述】:
下面发布的代码连接到 oracle 数据库,处理 SQL 查询并将结果表保存在新工作簿中。它适用于大约 200.000 行。但是,对于较大的数据集,当我尝试将数据从记录集对象复制到工作簿时,会发生错误 Method 'CopyFromRecordset' of object 'Range' failed:
dataWs.Range("A2").CopyFromRecordset dataset
有什么解决办法吗?我尝试遍历数据集的所有元素并将它们复制到工作表中,但是对于大数据集来说这需要很长时间。你有什么想法?我感谢您的帮助!现在是代码:
Sub QueryExecute(sqlString, userPW, userID, serverName)
'Connect to database <serverName> using user name <userID> and
'password <userPW> to process SQL query <sqlString> and save the
'query result in a new workbook
Dim ConnStr As String
Dim Cn As ADODB.Connection
Dim dataset As ADODB.Recordset
Dim dataWs As Worksheet
Dim dataWb As Workbook
Dim icols As Integer
'Create new workbook that will hold the query result/table:
Set dataWb = Excel.Application.Workbooks.Add
Set dataWs = dataWb.Sheets(1)
Application.Calculation = xlManual
'Trim trailing/leading blanks from sqlString:
sqlString = Trim(sqlString)
'Create string for database connection:
ConnStr = "UID=" & userID & ";PWD=" & userPW & ";DRIVER={Microsoft ODBC for Oracle};" _
& "SERVER=" & serverName & ";"
'Connect to database:
Set Cn = New ADODB.Connection
On Error Resume Next 'Error handling in case connection does not work
With Cn
.ConnectionString = ConnStr
.CursorLocation = adUseClient
.Open
End With
'Error handling for failed connection:
If Err.Number <> 0 Then
dataWb.Close
MsgBox "Connection to database failed. Check username and password."
Exit Sub
End If
'Send SQL query to database:
Set dataset = Cn.Execute(sqlString)
'Error handling for failed query:
If Err.Number <> 0 Then
dataWb.Close
MsgBox "SQL-query could not be processed."
Exit Sub
End If
On Error GoTo 0
'Copy column names in first row of table worksheet:
For icols = 0 To dataset.Fields.count - 1
dataWs.Cells(1, icols + 1).Value = dataset.Fields(icols).Name
Next
dataWs.Range(dataWs.Cells(1, 1), _
dataWs.Cells(1, dataset.Fields.count)).Font.Bold = True 'Format column names
'Copy data to workbook:
'***THIS WILL FAIL FOR LARGE DATASETS***
dataWs.Range("A2").CopyFromRecordset dataset
dataset.Close
Cn.Close
MsgBox "Query successful."
Application.Calculation = xlCalculationAutomatic
End Sub
【问题讨论】:
-
你试过
GetRows吗?不过,您需要先转置数组,然后再将其放入工作表中。 -
我将数据分配给了一个数组,但是对于大数据集,我在尝试将 GetRows 分配给数组时会收到内存不足错误。
-
您的较大数据集的记录中是否有任何非常长的文本值出现在有效的较小数据集中?
标签: sql-server oracle vba excel