[英]Excel VBA Access
I have the following code, where .Fields... is not getting executed. 我有以下代码,其中.Fields ...没有得到执行。 Loop is directly closing the connection without adding records into table. 循环直接关闭连接,而没有在表中添加记录。
Code: 码:
Sub insertIntoTable()
Dim moviesConn As ADODB.Connection
Dim moviesData As ADODB.Recordset
Dim moviesField As ADODB.Fields
Dim r As Range
Set moviesConn = New ADODB.Connection
Set moviesData = New ADODB.Recordset
moviesConn.ConnectionString = conStrAccess
moviesConn.Open
On Error GoTo closeConnection
With moviesData
.ActiveConnection = moviesConn
.Source = "tblFilmDetails"
.LockType = adLockOptimistic
.CursorType = adOpenForwardOnly
.Open
On Error GoTo closeRecordset
For Each r In Range("A3", Range("A2").End(xlDown))
.AddNew
.Fields("Title").Value = r.Offset(0, 1).Value
.Fields("Release_Date").Value = r.Offset(0, 2).Value
.Fields("Length").Value = r.Offset(0, 3).Value
.Fields("Genere").Value = r.Offset(0, 4).Value
.Update
Next r
End With
closeRecordset:
moviesData.Close
closeConnection:
moviesConn.Close
End Sub
Please suggest 请建议
I was able to get your code to work using this connection string: 我可以使用以下连接字符串使您的代码正常工作:
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\best buy\\Desktop\\test.accdb;Persist Security Info=False;" “提供程序= Microsoft.ACE.OLEDB.12.0;数据源= C:\\ Users \\ Best Buy \\ Desktop \\ test.accdb;持久安全信息= False;”
We can rule out data mismatch error because it throws a 3219 Runtime Error Operation before closing the connection. 我们可以排除数据不匹配错误,因为它会在关闭连接之前引发3219 Runtime Error Operation。
Range("A3", Range("A2").End(xlDown))
should probably be changed Range("A2", Range("A" & Rows.Count).End(xlup))
for two reasons: Range("A3", Range("A2").End(xlDown))
应该更改为Range("A2", Range("A" & Rows.Count).End(xlup))
,原因有两个:
If you have a large dataset you should comment out .Update
and use .UpdateBatch
after you have added all the records. 如果数据集.Update
, .UpdateBatch
在添加所有记录后注释掉.Update
并使用.UpdateBatch
。 This will greatly improve performance. 这将大大提高性能。
For Each r In Range("A3", Range("A2").End(xlDown))
.AddNew
.Fields("Title").Value = r.Offset(0, 1).Value
.Fields("Release_Date").Value = r.Offset(0, 2).Value
.Fields("Length").Value = r.Offset(0, 3).Value
.Fields("Genere").Value = r.Offset(0, 4).Value
'.Update
Next r
.UpdateBatch
Note: If you have the table open while adding the records then you have to press F5 to refresh the table and view the new data. 注意:如果在添加记录时打开了表,则必须按F5刷新表并查看新数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.