简体   繁体   中英

Excel VBA: Formulas not working with CopyFromRecordset, only when manually inserted

My formulas won't recalculate when i insert CopyFromRecordset, only if I insert it manually from an SQL query.

I have a connection set up to a SQL table, which returns a set of rows and inserts them into my table. In the same sheet, I have a few formulas (SUM.IF types) in a column next to the data. The connection works fine, the inserted data looks fine. When I copy the data from SQL query and insert into my excel sheet, the formulas can recalculate and works. When I use my CopyFromRecordset, the formulas will not recalculate and just outputs "-".

Cell formats are not changed. The formulas still look right and the same when I have insert CopyFromRecordset. Why won't the formulas update when I try to recalculate??

The code I use:

sht.Select
//Selects old records and clears them
LastRow = sht.Cells(sht.Rows.Count, "B").End(xlDown).Row
Set DataRange = Range("A2:L" & LastRow)
DataRange.Select
DataRange.ClearContents
//Gets data from SQL query and inserts to sheet
strSQL = "selects column 1,2,3 from table"
rs.ActiveConnection = Conn
rs.Open strSQL, Conn, 1, 1
sht.Range("A2").CopyFromRecordset rs

And all I get from my SUM.IF formula is "-".

Okay, so the problem was that the column containing numbers was not formatted corretly. The excel column was correctly formatted, but apparently the data coming from SQL was sent in varchar format. So the CopyFromRecordset just pours the data into the sheet, and the numbers didn't get re-formatted, and my SUMIF() wouldn't accept it as numbers. I just changed my sql line to convert that column into float

strSQL = "SELECT  CONVERT(float,[numberColumn]) AS [number], column2, column3"

Everything works fine now! :D

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM