问题
i'm writing a VBA macro for Excel 2003. I'm importing various data from a sql database to the Excel sheets.
I tried two ways to do that:
QueryTables.Add(...)
- with ADO
I was in favour of ADO, because it seemed to be the 'better' or 'cleaner" solution.
Everything worked well until i tried to get a numeric value with ADO out of the database. Instead of returning the value 1842,47078
it returned 0,01842
. (just to show what i mean)
Strange thing is: when i try it with QueryTables.Add(...)
i get the right value.
I have totally no clue why this happens, searched the internet for a solution but didn't found anything. It just happens with numeric values. If i get a string from the database everything is fine.
Can anyone help me with this one?
Driver is Firebird/InterBase(r) driver connecting with ODBC. Here is a little example how i do things:
'ADO solution = wrong value
With adoConnection
.Provider = "MSDASQL"
sConnection = "ODBC;DSN=ABC;Driver=Firebird/InterBase(r) driver;Dbname=blaName.gdb;"
ConnectionString = sConnection
.Open
End With
SQL_Import = "SELECT A.PRICE AS ""Price"" FROM TABLE A WHERE A.KEY ='x1234' "
adoRecordset.ActiveConnection = adoConnection
adoRecordset.Open SQL_Import
varSol = adoRecordset.Fields("Price")
Sheets(3).Cells(1, 1).Value = varSol
adoRecordset.Close
adoRecordset.ActiveConnection = Nothing
adoConnection.Close
'QueryTables solution = right value
Set QueryTbl = Sheets(3).QueryTables.Add(Connection:=sConnection, Destination:=Sheets(3).Cells(1, 2))
With QueryTbl
.CommandText = SQL_Import
.AdjustColumnWidth = True
.Refresh BackgroundQuery:=False
.Delete
End With
I hope anyone can help me.
Update:
- I got it working somehow, but i don't know what was wrong.
- I get the right results if i use the query
SELECT Price as numeric(15, 2)...
. - Strange thing is that i tried the whole thing with C# on my computer and it worked without any problems. So the error seems to be caused by anything in Excel and/or VBA.
回答1:
Try applying a NumberFormat to the cell
varSol = adoRecordset.Fields("Price")
Sheets(3).Cells(1, 1).NumberFormat = "###0,#######0"
Sheets(3).Cells(1, 1).Value = varSol
回答2:
I don't know anything about firebird but it sounds like the column in question is in Money or Currency type (what ADO calls adCurrency) and you haven't told ADO this, so it's not converting it appropriately.
Look at adoRecordset.Fields("Price").Type and I'll bet you'll see that it's adCurrency or the like.
回答3:
I don't know really what the problem is/was, but i have a solution. If i alter my SQL string to
SQL_Import = "SELECT A.PRICE*1 FROM TABLE A WHERE A.KEY ='x1234' "
everything works as expected and i get the right result.
So my solution is multiplying with one or adding zero.
来源:https://stackoverflow.com/questions/7818220/ado-returns-wrong-order-of-magnitude