Excel VBA:csv文件的SQl查询返回的是整数而不是double

时间:2019-05-22 16:07:51

标签: sql excel vba csv ado

在Excel中,我有使用ADO为csv文件创建查询的VBA代码。该查询将一些选择字段返回到Recordset中,然后我将其提取出报告所需的数据。该字段包含字符串和数字值。

只要该字段中的第一个数字为双精度值,代码就可以正常工作,但是如果该值是整数,则所有数字都将转换为整数,这并不能满足我想要的结果。

这是我设置查询并获取Recordset的方法:

Private Function getRecordSet(ByVal fileSource As String, ByVal fileName As String) As ADODB.Recordset

    Dim con As New ADODB.Connection
    Dim cmd As New ADODB.command
    Dim rs As ADODB.Recordset

    'set up connection to file source
    con.Provider = "Microsoft.Jet.OLEDB.4.0"
    con.ConnectionString = _
        "Data Source=" & fileSource & ";" & _
        "Extended Properties=""text; HDR=Yes; FMT=Delimited; IMEX=1;"""
    con.Open
    con.CursorLocation = adUseClient
    cmd.ActiveConnection = con

    'set up and execute query
    cmd.CommandText = _
        "SELECT [Total Test Timer], [Stage], [Corrected Blowby] " & _
        "FROM " & fileName & " " & _
        "WHERE [Stage] = 1"
    Set rs = cmd.Execute

    'disconnect the record set from the file source
    rs.ActiveConnection = Nothing

    'clean up ADO objects
    Set cmd = Nothing
    If Not con Is Nothing Then
        If con.State = adStateOpen Then con.Close
        Set con = Nothing
    End If

    'return Recordset
    Set getRecordSet = rs

End Function

这里是示例数据集,其中的代码按预期工作(发生错误的字段为“校正后的漏斗”:

Total Test Timer,Stage,Corrected Blowby
,,LPM
,,SC1Mod4/ai25
1.04167,1,21.85
1.05,1,21.85
1.05833,1,35.48
1.06667,1,35.48
1.075,1,35.48
1.08333,1,35.48
1.09167,1,35.48

这是一个示例数据集,其中所有数值都转换为整数:

Total Test Timer,Stage,Corrected Blowby
,,LPM
,,SC1Mod4/ai25
1.025,1,0
1.03333,1,0
1.04167,1,0
1.05,1,0
1.05833,1,21.43
1.06667,1,21.43
1.075,1,21.43

我尝试将“校正后的Blowby”字段转换为字符串和双精度字符:

"SELECT [Total Test Timer], [Stage], cStr([Corrected Blowby]) AS newField " & _

并且:

"SELECT [Total Test Timer], [Stage], cDbl([Corrected Blowby]) AS newField " & _

,但都不起作用。有人对如何进行有任何建议吗?谢谢!

0 个答案:

没有答案