问题
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