删除表中的所有记录 - doCMD.RunSQL

时间:2014-03-04 13:47:43

标签: sql vba excel-vba access-vba ms-access-2013

我希望在向其添加新数据之前清除所有记录的本地表。我试图使用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

1 个答案:

答案 0 :(得分:2)

对于您将使用的本地数据库:CurrentDb.Connection.Execute "DELETE * FROM Table1"

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