Get decimals from Recordset in VBA with ADODB

2019-08-06 07:29发布

I'm trying to get a value from a field, I don't know why is rounded

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

For example, in the database S1 is 8.567 but I always get 8

Is there a way to define the data type from that field?

Thank you!

2条回答
在下西门庆
2楼-- · 2019-08-06 07:51

I found the solution, in your query you have to define the type of data you want to have.

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

Then you will get newValue with decimals.

查看更多
姐就是有狂的资本
3楼-- · 2019-08-06 08:04

Declare and assign your variables properly.

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

I don't like the orphaned Cells(i, 1) either. That should have a defined parent worksheet. Perhaps a wrapping With ... End With statement could be used to specify parentage.

查看更多
登录 后发表回答