ADODB Excel SQL 语句写入下一个可用行

ADODB Excel SQL statement to write to next available row

我目前能够通过在我的 VBScript 中使用 ADODB 连接来读取和更新我的 Excel 电子表格中的数据。这工作很顺利,我知道如何随心所欲地操纵不同的列和不同的行。

我的问题是,我现在需要输入一行新数据。它怎么知道把它放在哪里?我一直在使用的代码总是提供某种参考点:示例:

rs.Open "Update [links$] Set [F" & arrLocals(i) & "]= '" & arrChangeData(i) & "' Where [F2] = '" & arrFormID(j) & "'", cn, adOpenStatic, adLockOptimistic

所以据此,只要您在 arrFormID(j) 匹配列 F2.[=22 的行上工作,这几乎意味着 对该行做一些事情=] 但是,如果你想要一个新行,我不知道要匹配什么?

您需要使用 insert 语句。 SQL 语句,如 insertdeleteupdate 通常不会被视为 "row-returning" 语句,因此通常使用 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 语句只是为 table/worksheet 中的每一列提供值,这些列以相同的顺序出现:

cn.Execute "insert into [links$] values ('col1value','col2value','col3value')"

另一种方法是使用 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