CopyFromRecordset 返回奇怪的字符

CopyFromRecordset Returning Strange Characters

我有以下代码:

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 行 returns 非常奇怪的字符数据,它也是直接从 SQLServer 中的 QA 数据库复制的。当我说非常奇怪时,我的意思是比如空格和日式字符混合在一起,或者一些我什至不认识的字体集。

rsPubs returns 准确的记录计数符合预期,所以我知道我得到了我想要的结果。还确认数据已根据需要写入 SQLServer 数据库。

关于如何修复它以便从调用 Prod SQLServer DB 得到的值 return 有任何想法吗?

我也遇到了类似的问题,我强烈怀疑您的 RecordSet 中返回的记录数非常大。因此,CopyFromRecordSet 不起作用。

我建议使用以下方法:

  1. 用 RecordSet 数据填充 VBA 中的二维数组。

    变暗 arr arr=rs.GetRows() rs.close conn.close

  2. 转置数组(因为这会导致倒置数组)

    arr=Application.WorksheetFunction.Transpose(arr)

  3. 数组转置后,即可将数组写入工作表Range

    testWS.Range("A1").Resize(UBound(arr, 1) + 1, UBound(arr, 2)

这对我有用。希望对你有用!

编码愉快!

我最终遍历了记录集并将每个值一个接一个地放置。也就是说,提供的数组答案对于大型数据集可能会更快。当时,这符合我的需要并且有效。

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

            r = 0

            DestinationRange.ClearContents
            '.CopyFromRecordset rsPubs 'this is breaking on PDLOBList download (last column not showing up) 'PAQPT-488

            If .RecordCount > 0 Then
                .MoveFirst
                Do Until .EOF
                    For c = 0 To .Fields.Count - 1
                        DestinationRange.Offset(r, c).value = .Fields(c)
                    Next
                    .MoveNext
                    r = r + 1
                Loop

(我省略了 if 块的其余部分,因为它们与此答案无关。)