使用 ADODB 从 VBA 中的记录集中获取小数

Get decimals from Recordset in VBA with ADODB

我正在尝试从字段中获取值,我不知道为什么要四舍五入

rs.Open myQuery, cnn
i = 1
Do While rs.EOF = False
    S1 = rs.Fields("S1") 
    Cells(i, 1) = S1
    i = i + 1
    rs.Next
Loop

例如,在数据库S1中是8.567,但我总是得到8

有没有办法从该字段定义数据类型?

谢谢!

正确声明和分配变量。

dim S1 as double   '<~~declare a double-type variable
rs.Open myQuery, cnn
i = 1
With Worksheet("Sheet1")   'define the parent worksheet
    Do While Not rs.EOF
        S1 = CDbl(rs.Fields("S1").Value)  '<~~ force a double-type return and specify the value
        .Cells(i, 1) = S1    '<~~ the prefix period (.) determines that this belongs to Sheet1
        i = i + 1
        rs.Next
    Loop
end with

我也不喜欢孤儿Cells(i, 1)。那应该有一个已定义的父工作表。也许包装 With ... End With statement 可用于指定出身。

我找到了解决方案,在您的查询中您必须定义您想要的数据类型。

sqlQuery = "SELECT CAST(F1 AS DOUBLE) AS newValue FROM TABLE"

然后你会得到带小数的newValue。