VBA SQL返回空值

时间:2018-11-22 23:00:07

标签: sql sql-server excel vba excel-vba

我在vba excel上运行SQL语句时遇到问题,最后3列用于存储用逗号分隔的数字,但是在excel vba上执行时,它不显示这些值,而在其他数据库程序中却显示

代码如下

Sub obtainColMachs()    
    Dim cnn1 As New ADODB.Connection
    Dim mrs As New ADODB.Recordset, sqry As String

    Set cnn1 = New ADODB.Connection
        cnn1.ConnectionString = "driver=SQL Server Native Client 11.0;" & _
        "server=server;uid=user;pwd=password;database=DB;"
        cnn1.ConnectionTimeout = 3
        cnn1.Open

    sqry = "select top 1 m.* from recipe r left join RecipeGroup rg on r.RecipeGroupID = rg.RecipeGroupID " & _
    "left join Matricula m on tonalidad_ID = ParentGroupID *100 + rg.RecipeGroupID where Substring(ColorNo,3,3) = 'ZG5'"

    mrs.Open sqry, cnn1
    Range("A26").CopyFromRecordset mrs

    mrs.Close
    cnn1.Close
End Sub

它应该返回:

Data returned on Database program

但是它只会返回:

Data returned in VBA Excel

1 个答案:

答案 0 :(得分:1)

您似乎只从Matricula表中返回字段;也许SQL应该是:

select top 1 m.*, r.*, rg.* from

或者更好的是,列出实际需要的字段并参考它们源自的表,例如:

select top 1 m.Tonalidad, m.Field2, r.Field3, rg.Field4 etc... from