2014-03-04 143 views
0

我正在寻找清除所有记录的本地表,然后向其中添加新数据。我正在尝试使用doCMD.RunSQL命令执行此操作,但由于它位于打开的连接中,我一直在猜测运行时错误,所以我不确定如何让它执行。从表中删除所有记录 - doCMD.RunSQL

任何帮助表示赞赏。

感谢

Sub GetUsers() 
    Dim oConnection As Object 
    Dim oSheet As Object 
    Dim oCell As Object 
    Set oConnection = CreateObject("ADODB.Connection") 
    Dim strDBPath As String 
    strDBPath = "C:/Users/stevemcco/Desktop/Users.accdb" 
    Dim sConn As String 
    sConn = "Provider=Microsoft.ACE.OLEDB.12.0;" & _ 
         "Data Source=" & strDBPath & ";" & _ 
         "Jet OLEDB:Engine Type=5;" & _ 
         "Persist Security Info=False;" 

    oConnection.Open sConn 

    DoCmd.RunSQL "Delete * from Table1" 

    For Each oSheet In ThisWorkbook.Sheets 
     For Each oCell In oSheet.Columns(1).Cells 
      If oCell.Value = "" Then 
       Exit For 
      End If 

      If (oCell.Row > 1) Then 'Jumps the header 
       oConnection.Execute " Insert Into Table1(ID,Area) " _ 
       & " VALUES ('" & oCell.Value & "','" & oSheet.Name & "')" 
      End If 

     Next 
    Next 
    oConnection.Close 
    Set oConnection = Nothing 
End Sub 
+0

没有在Excel中没有DoCmd对象。 –

+0

我不得不添加MS DAO 3.6对象库的参考,使其可见。仍然无法让它工作在你的脑海中。 – StevenM

回答

2

对于本地数据库可以使用:CurrentDb.Connection.Execute "DELETE * FROM Table1"

在你的情况下使用:oConnection.Execute "DELETE * FROM Table1"

+0

完美!这样做巧妙地谢谢你! – StevenM

+0

如果我想查询这个新的表格数据,并将任何重复项返回到我的主Excel表格上,我该怎么做? – StevenM