2014-03-04 142 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