ADO记录集不返回DSN的字段值;使用连接字符串

时间:2017-03-17 19:00:22

标签: excel-vba connection-string ado dsn vba

我有以下功能:

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
Dim sqlstring As String

Dim s As String

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 below that is not relevant

假设我把这个函数称为:

Dim conPDDB As New ADODB.Connection
conPDDB.Open "myConnectionString" - see below

Dim sSQL as String
sSQL = "SELECT ... "

downloadsqltoexcel conPDDB, sSQL, "DSN", "", True, Sheet1

如果我将硬编码连接字符串传递给myConnectionString,我会得到我想要的结果。如果我传递DSN连接字符串,则最后一列数据不会转储到Excel中。

见图片

enter image description here

  

Provider = SQLOLEDB; Data Source = MYSERVER; Initial Catalog = MYDB; User   Id = MYUID;密码= MYPWD

     

DSN = PDDB_QA; UID = MYUID; PWD = MYPWD(DSN configmirrors连接字符串)

字段本身正在返回,因为当我将?rsPubs.Fields(5).Value打印到即时窗口时,我收到AU,CI,GL,IM,PF作为回报。在此示例中,最后一个数据有逗号,但它并不总是逗号。我尝试过使用DSN设置和rs.Open参数。徒劳无功。

有人有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我现在将此作为答案,但我对解决方案不满意。 (我现在将实施,因为发布时间是两周之后,还有很多的更多工作要做)。

如果我找不到或没有人提供更好的解决方案,我会接受这个并继续前进。

Text Label1行重构为下面的行,带上最后一列。

.CopyFromRecordset rsPubs
相关问题