使用SQL的Delete语句中删除指定记录时,一定要指定Where子句,不然会删除表中所有记录。
如下,先指定需要删除的记录的“客户ID”:
编写如下代码:
Sub 删除记录()
Dim cnn As New Connection
Dim strcon As String, strSql As String, custID As String
custID = Worksheets("修改").Range("B1")
If Trim(custID) = "" Then
MsgBox "请输入“客户ID”信息!", vbCritical + vbOKOnly
Exit Sub
End If
On Error Resume Next
strcon = "Provider=Microsoft.Jet.OLEDB.4.0;" _
& "Data Source=" & ThisWorkbook.Path & "\Northwind.mdb"
cnn.Open strcon '打开数据库连接
strSql = "DELETE FROM 客户 WHERE 客户ID='" & custID & "'" '删除"客户"表的SQL语句
cnn.Execute (strSql)
If Err <> 0 Then '显示错误信息
MsgBox Err.Description
End If
cnn.Close
Set cnn = Nothing
End Sub
上述代码运行下,指定的记录在数据库中即被删除。
-End-