【发布时间】:2018-07-12 15:17:22
【问题描述】:
我在 Excel 上有一个表格,范围 A1:Sn(其中 n 是 LastRow)。以前我习惯在每一行中循环并一一插入。
这很好用,我可以求助于它,但我希望将整个记录集("A1:S" & LastRow) 插入 SQL 表,而不是逐行循环。
这样做的原因是,如果我将整个记录集插入将被视为 1x 操作,因此将为多个用户生成收据 ID 会变得非常容易。
代码
Dim con As ADODB.Connection
Dim rs As ADODB.Recordset
Set con = New ADODB.Connection
Set rs = New ADODB.Recordset
dim i as long
dim LastRow as long
LastRow = Sheets("Project_Name").Cells(Rows.count, "B").End(xlUp).row
con.Open "Provider=SQLOLEDB; Data Source=LO1WPFSASDB001 ; Initial Catalog=database; User ID=username; Password=password; Trusted_Connection=no"
rs.Open "SELECT * from table;", con, adOpenKeyset, adLockOptimistic
With rs
for i = 1 to LastRow
.addnew
!somevalue = range("A1:S" & LastRow)
.update
next
.Close
End With
con.Close
Set con = Nothing
Set rs = Nothing
我似乎无法让它工作。我会很感激你的意见。
【问题讨论】:
-
循环后调用更新?
-
对不起.. 请详细说明?
-
我认为您可以添加到记录集,然后在您进行更新后进行更新。
-
考虑使用 MS Access 将数据存储在表中,以便对 SQL Server 进行批量追加查询。