我在下面有以下代码:
Function downloadsqltoexcel(conn As ADODB.Connection, sSQL As String, exceldestinationrangename As String, sqltablename As String, bDownload As Boolean, Optional ws As Worksheet) As Variant
'================================================================================================================================
'== Procedure Name: downloadsqltoexcel
'== Purpose: downloads SQL table data (or query data) to Excel named range or grabs a specific value from an SQL table
'== Notes: ensure that SQL table or query name and Excel named range are identical
'================================================================================================================================
Dim rsPubs As ADODB.Recordset
Set rsPubs = New ADODB.Recordset
Dim DestinationRange As Range
With rsPubs
.ActiveConnection = conn
.Open sSQL, conn, adOpenStatic, adLockReadOnly, adCmdText
If bDownload Then 'if download switch is on, dump into Excel named range
If ws Is Nothing Then
Set DestinationRange = Range(exceldestinationrangename)
Else
Set DestinationRange = ws.Range(exceldestinationrangename)
End If
With DestinationRange
.ClearContents
.CopyFromRecordset rsPubs
End With
.... more code follows, but not relevant
代码本身执行良好。但是,当我指向新创建的Prod SQLServer数据库时,.CopyFromRecordset rsPubs
行返回非常奇怪的字符数据,该数据库也是直接从SQLServer中的QA数据库复制的。字符或某些字体集,我什至不认识。
rsPubs
返回预期的确切记录数,所以我知道我得到了想要的结果。还要确认已根据需要将数据写入SQLServer DB。
任何想法如何解决它,以便值从Prod SQLServer DB的调用中按预期返回?
我也遇到了类似的问题,我强烈怀疑RecordSet中返回的记录数量很大。因此,CopyFromRecordSet
不起作用。
我建议使用以下方法:
在VBA中使用RecordSet数据填充二维数组。
Dim arr as Variantarr = rs.GetRows()rs.closeconn.close
转置数组(因为这将导致倒置数组)
arr = Application.WorksheetFunction.Transpose(arr)
一旦数组被转置,您就可以将数组写入工作表范围。
testWS.Range(“ A1”)。Resize(UBound(arr,1)+ 1,UBound(arr,2)
这对我有用。希望对您有用!编码愉快!