简体   繁体   English

使用ADODB Recordset更新记录

[英]Updating records with ADODB Recordset

I need to update a recordset in Excel VBA. 我需要在Excel VBA中更新记录集。 I extract the data from a CSV and use the Text driver to connect to the file. 我从CSV中提取数据并使用文本驱动程序连接到该文件。 Here is my connection to the file, recordset and update code. 这是我与文件,记录集和更新代码的连接。

Dim con As New ADODB.Connection
Dim rs As New ADODB.Recordset
con.Open "Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=C:\Users\jasons\Documents\sl;Extensions=csv;"

rs.Open "SELECT *, 0 As item FROM Pct.csv where [Sku No] in ('123455','123456')", con, adOpenDynamic, adLockOptimistic


rs.MoveFirst
Do Until rs.EOF
rs.Fields(0) = 2
rs.MoveNext
Loop

But I keep getting the following error message at the rs.MoveNext line. 但是我一直在rs.MoveNext行收到以下错误消息。

-2147467259-[Microsoft][ODBC Text Driver] Syntax error (missing operator) in query expression '(item=Pa_RaM001 AND Style Code=Pa_RaM002 AND Sku No=Pa_RaM003'. -2147467259- [Microsoft] [ODBC文本驱动程序]查询表达式中的语法错误(缺少运算符)'(item = Pa_RaM001 AND St​​yle Code = Pa_RaM002 AND Sku No = Pa_RaM003'。

When i remove the loop and update the first record as 当我删除循环并将第一条记录更新为

rs.MoveFirst
rs.Fields(0) = 2

then it works. 然后它工作。 I looked on the internet for examples and but i can not see what i am doing wrong. 我在网上看了一些例子,但我看不出我做错了什么。 I would appreciate any assistance. 我将不胜感激任何帮助。

You could use the following approach to generate CSV files with ADODB. 您可以使用以下方法使用ADODB生成CSV文件。 UPDATE CSV files is definitely a very bad idea. 更新CSV文件肯定是一个非常糟糕的主意。 ALTER TABLE is also impossible in my opinion. 在我看来,ALTER TABLE也是不可能的。 So the approach will CREATE a new temporary table with the new field. 因此,该方法将使用新字段创建一个新的临时表。 Then copying the data from the old table and setting the data of the new field. 然后从旧表中复制数据并设置新字段的数据。 And at last swapping the temporary table into the CSV file. 最后将临时表交换到CSV文件中。

Sub ADODB_CSV()

 Dim con As New ADODB.Connection

 con.Open "Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=C:\Users\jasons\Documents\sl;Extensions=csv;"

 On Error Resume Next
 con.Execute "DROP TABLE temp.csv"
 On Error GoTo 0

 con.Execute "CREATE TABLE temp.csv (item integer, [Style Code] text, [Sku No] text)"

 con.Execute "INSERT INTO temp.csv (item, [Style Code], [Sku No]) SELECT 0, [Style Code], [Sku No] FROM Pct.csv WHERE [Sku No] NOT IN ('123455','123456')"
 con.Execute "INSERT INTO temp.csv (item, [Style Code], [Sku No]) SELECT 2, [Style Code], [Sku No] FROM Pct.csv WHERE [Sku No] IN ('123455','123456')"

 con.Execute "DROP TABLE Pct.csv"
 con.Execute "CREATE TABLE Pct.csv (item integer, [Style Code] text, [Sku No] text)"

 con.Execute "INSERT INTO Pct.csv SELECT * FROM temp.csv"

 con.Execute "DROP TABLE temp.csv"

 con.Close

End Sub

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

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