我尝试将存储在Excel电子表格中的数据添加到访问数据库。但是,在添加每一行之前,我想检查数据库中是否已存在该行数据,如果是,请跳过该行并移至下一行。请避免重复数据..
从一个完全空白的数据库中,我的代码输入前两行数据,然后抛出错误。
错误3704关闭对象时不允许操作
当我停止然后再次运行代码时,输入接下来的两行数据并再次弹出错误!等等...
我是ADO的新手,无法弄清问题是什么,所以非常感谢所有的帮助。
以下是完整的代码块:
Function GetDb() As ADODB.Connection
Set GetDb = New ADODB.Connection
GetDb.Open "Provider=Microsoft.ACE.OLEDB.12.0;DATA Source=" & GetPath & ";"
End Function
Function GetPath() As String
GetPath = ThisWorkbook.Path & "\db.accdb"
End Function
Sub AddToDBSTACKFB()
'searchfirst try
Dim adoConn As ADODB.Connection
Dim adoComm As New ADODB.Command
Dim adoRS As Recordset
Dim RecordRow As Long, Lastrow As Long
Dim OrderID As String, Site As String, ProductName As String
Dim ShipTo As String, ShipVia As String, Quantity As Long, Email As String
Set adoConn = GetDb
Lastrow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Row
With adoComm
Set .ActiveConnection = adoConn
.CommandText = "select [OrderID],[Site],[Product Name],[Ship To],[Ship Via],[Quantity],[Email] " & _
"FROM DATA " & _
"where [OrderID] =? and [Site] = ? and [Product Name] = ? and [Ship To] = ? and [Ship Via] = ? and [Quantity] = ? and [Email]= ?"
.Parameters.Append adoComm.CreateParameter(Name:="OrderID", Type:=adVarChar, Size:=255)
.Parameters.Append adoComm.CreateParameter(Name:="Site", Type:=adVarChar, Size:=255)
.Parameters.Append adoComm.CreateParameter(Name:="Product Name", Type:=adVarChar, Size:=255)
.Parameters.Append adoComm.CreateParameter(Name:="Ship To", Type:=adVarChar, Size:=255)
.Parameters.Append adoComm.CreateParameter(Name:="Ship via", Type:=adVarChar, Size:=255)
.Parameters.Append adoComm.CreateParameter(Name:="Quantity", Type:=adDouble)
.Parameters.Append adoComm.CreateParameter(Name:="Email", Type:=adVarChar, Size:=255)
'Loop through all the records on the sheet one row at a time
For RecordRow = 2 To Lastrow
OrderID = Sheet1.Cells(RecordRow, 1).Value
Site = Sheet1.Cells(RecordRow, 2).Value
ProductName = Sheet1.Cells(RecordRow, 3).Value
ShipTo = Sheet1.Cells(RecordRow, 4).Value
ShipVia = Sheet1.Cells(RecordRow, 5).Value
Quantity = Sheet1.Cells(RecordRow, 6).Value
Email = Sheet1.Cells(RecordRow, 7).Value
.Parameters(0).Value = OrderID
.Parameters(1).Value = Site
.Parameters(2).Value = ProductName
.Parameters(3).Value = ShipTo
.Parameters(4).Value = ShipVia
.Parameters(5).Value = Quantity
.Parameters(6).Value = Email
'First, check if the record is already in the database
'if its not, then enter that row of data into the database
Set adoRS = adoComm.Execute
If (adoRS.EOF And adoRS.BOF) Then '<< ERROR ON THIS LINE EACH TIME
adoComm.CommandText = "INSERT INTO DATA([OrderID],[Site],[Product Name],[Ship To],[Ship Via],[Quantity],[Email]) " & _
"VALUES(?,?,?,?,?,?,?)"
adoComm.Execute
Set adoRS = Nothing
Else
Set adoRS = Nothing
End If
Next RecordRow
End With
adoConn.Close
End Sub