简体   繁体   English

Excel VBA:仅当手动插入时,公式不能与CopyFromRecordset一起使用

[英]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. 仅当我从SQL查询中手动插入CopyFromRecordset时,我的公式才会重新计算。

I have a connection set up to a SQL table, which returns a set of rows and inserts them into my table. 我有一个到SQL表的连接,该表返回一组行并将它们插入到我的表中。 In the same sheet, I have a few formulas (SUM.IF types) in a column next to the data. 在同一张纸上,我在数据旁边的列中有一些公式(SUM.IF类型)。 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. 当我从SQL查询复制数据并将其插入到Excel工作表中时,公式可以重新计算并起作用。 When I use my CopyFromRecordset, the formulas will not recalculate and just outputs "-". 当我使用CopyFromRecordset时,公式将不会重新计算,而只会输出“-”。

Cell formats are not changed. 单元格格式不变。 The formulas still look right and the same when I have insert CopyFromRecordset. 当我插入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 "-". 我从SUM.IF公式中得到的全部是“-”。

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. excel列的格式正确,但是显然来自SQL的数据是以varchar格式发送的。 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. 因此,CopyFromRecordset只是将数据倒入工作表中,并且数字没有重新格式化,而我的SUMIF()则不接受它作为数字。 I just changed my sql line to convert that column into float 我只是更改了我的sql行以将该列转换为float

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

Everything works fine now! 现在一切正常! :D :D

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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