我目前能够使用VBScript中的ADODB连接读取和更新Excel电子表格中的数据。这很顺利,我理解如何用我想要的任何方式操纵不同的列和不同的行。
我的问题是,我现在需要输入一行新数据。它是如何知道放在哪里的?我一直在使用的代码总是提供某种参考点:例如:
rs.Open "Update [links$] Set [F" & arrLocals(i) & "]= '" & arrChangeData(i) & "' Where [F2] = '" & arrFormID(j) & "'", cn, adOpenStatic, adLockOptimistic
所以根据这一点,只要你在arrFormID(j)
匹配列F2
的行上工作,它就意味着对这一行做了什么。但是,如果你想要一个新的行,我不知道有什么可以匹配?
答案 0 :(得分:3)
您需要使用insert
语句。像insert
,delete
和update
这样的SQL语句通常不被视为"行返回"语句,因此使用Connection
对象本身来执行操作而不是Recordset
通常更有意义。例如:
Dim cn
Set cn = CreateObject("ADODB.Connection")
cn.Open "<your Excel connection string>"
cn.Execute "update [links$] set ... where ..."
cn.Execute "insert into [links$] values (...)"
cn.Execute "delete from [links$] where ..."
cn.Close
最基本的insert
语句只为表/工作表中的每一列提供值,列的显示顺序相同:
cn.Execute "insert into [links$] values ('col1value','col2value','col3value')"
答案 1 :(得分:1)
另一种方法是使用RecordSet接口,例如:
Option Explicit
Const adCmdTable = 2
Const adLockBatchOptimistic = 4
Const adLockOptimistic = 3
dim ado, rs
set ado = CreateObject("ADODB.Connection")
set rs = CreateObject("ADODB.RecordSet")
ado.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=example.xlsx;Extended Properties=""Excel 12.0 Xml;HDR=YES"";"
ado.Open
'ado.Execute "DROP TABLE Sheet1"
ado.Execute "CREATE TABLE Sheet1 (ID int, name VARCHAR)"
rs.Open "Sheet1", ado, , adLockOptimistic, adCmdTable
dim i
for i = 0 to 4
' create a new record, populate the fields then update the data source
rs.AddNew
rs.Fields("ID").Value = i
rs.Fields("name").Value = "Dave"
rs.Update
next 'i
' also showing populating a dictionary to pass to update() instead
' of inserting into the record's fields directly
rs.AddNew
dim dict
set dict = CreateObject("Scripting.Dictionary")
dict("ID") = 99
dict("name") = "Geoff"
rs.Update dict.Keys(), dict.Items()
rs.Close
ado.Close
给你
ID | name ---------- 0 | Dave 1 | Dave 2 | Dave 3 | Dave 4 | Dave 99 | Geoff