您的位置:首頁>正文

VBA|資料庫操作05:通過Excel工作表修改記錄(Update改)

在VBA中, 使用Update語句可對資料庫中的記錄進行修改, 一般用where子句限制需要修改記錄的範圍。

下面用一個簡單的實例說明如何修改資料庫:

編寫代碼如下:

Sub 修改客戶名稱()

Dim cnn As New Connection, strcon As String

Dim strSql As String, custID As String, custName As String

With Worksheets("修改") '獲取輸入資訊

custID = .Range("B1") '獲取客戶ID

custName = .Range("B2") '獲取公司名稱

End With

If Trim(custID) = "" Or Trim(custName) = "" 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 = "UPDATE 客戶 SET 公司名稱='" & custName & _

"' WHERE 客戶ID='" & custID & "'" '修改"客戶"表的SQL語句

cnn.Execute (strSql) '執行SQL命令

cnn.Close

Set cnn = Nothing

End Sub

上面的代碼運行後, 資料庫中表“客戶”的記錄的“客戶ID”為TESTA的公司的名稱改為了“測試公司1"。

-End-

同類文章
Next Article
喜欢就按个赞吧!!!
点击关闭提示