Get decimals from Recordset in VBA with ADODB

你。 提交于 2019-12-11 10:41:37

问题


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!


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/34734877/get-decimals-from-recordset-in-vba-with-adodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!