我在Excel中编写此代码以插入访问数据库。
INSERT INTO `C:\Users\ABCBASDkJAJDSKk\Desktop\asdgahsdguu.accdb`.`Table1` Values ('ABCD', 'ABCD','ABCD,ABCD','NA','Success','Several of the above','NA','NA','NA','NA','NA','NA','NA','AB',12)
我收到错误在rs.open语句中,对象Recordset的方法打开失败。
有关为何发生这种情况的任何想法?
以下是代码
Sub merge_update()
Dim ws As Worksheet
Set ws = Sheets("Darwin Merge Set")
lastrow = ws.Range("B" & Rows.count).End(xlUp).Row
Dim cmd1 As ADODB.Command
Application.ScreenUpdating = False
Dim i As Integer
Dim cn As ADODB.Connection
Set cn = New Connection
strFile = "C:\Users\ABCBASDkJAJDSKk\Desktop\asdgahsdguu.accdb"
cn.Provider = " Provider=Microsoft.ACE.OLEDB.15.0 "
cn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.15.0;Data Source=" & strFile & ";Persist Security Info=false;"
Dim rs As New ADODB.Recordset
cn.Open
For i = 7 To lastrow
src = Range("b" & i).Value
tar = Range("c" & i).Value
dmc = Range("d" & i).Value
gl = Range("e" & i).Value
mo = Range("f" & i).Value
msa = Range("g" & i).Value
fm = Range("h" & i).Value
rsnm = Range("i" & i).Value
em = Range("j" & i).Value
sa = Range("k" & i).Value
rbsc = Range("l" & i).Value
qao = Range("m" & i).Value
qac = Range("n" & i).Value
lo = Range("o" & i).Value
mpl = Range("p" & i).Value
mon = Range("q" & i).Value
stmt = "INSERT INTO `" & strFile & "`.`Table1`"
stmt = stmt & " Values ('" & src & "', '" & tar & "','" & dmc & "','" & gl & "','" & mo & "','" & msa & "','" & fm & "','" & rsnm & "','" & em & "','" & sa & "','" & rbsc & "','" & qao & "','" & qac & "','" & mpl & "'," & mon & ") "
cmd1.ActiveConnection = cn
cmd1.CommandText = stmt
Set rs = cmd1.Execute
Next i
cn.Close
End Sub
答案 0 :(得分:0)
您没有使用命令对象,您想要用Command替换RecordSet。记录集是值从数据库返回的位置。
这里有一个链接,里面有很多很好的例子。
http://support.microsoft.com/kb/168336/en-us
一个例子(Dim cmd1行中的New很重要。
Dim cmd1 As New ADODB.Command
' Recordset Open Method #2: Open via Command.Execute(...)
Conn1.ConnectionString = AccessConnect
Conn1.Open
Cmd1.ActiveConnection = Conn1
Cmd1.CommandText = "SELECT * FROM Employees"
Set Rs1 = Cmd1.Execute
Rs1.Close
Conn1.Close
Conn1.ConnectionString = ""