[英]Access VBA to Update Table Record
我正在嘗試將代碼分配給 MS Access 中將更新表記錄的按鈕。 單擊按鈕時,我希望它在附近的列表框(List26)中引用用戶更新的項目編號,在表(資產)中查找匹配的項目編號字段,然后更改字段(所有者)記錄為空白。
我一直在挖掘並發現有關 DAO 記錄集的一些邏輯,但我對 VBA 不夠熟悉,無法正確設置或知道這是否是正確的路徑。 以下是我到目前為止所做的:
Private Sub Check_In_Device_Click()
Dim rec As DAO.Recordset
'Table1 called "Assets"
Set rec = CurrentDb.OpenRecordset("SELECT * FROM Assets")
'if the data in List26 matches an Item# in Asset table...
If [Item].value = [List26].value Then
rec.MoveFirst
rec.Edit
'change Owner field to null
rec![Owner].value = ""
rec.Update
rec.Close
End If
End Sub
項目可能是數字,並使用Null空白字段,因此嘗試:
Private Sub Check_In_Device_Click()
Dim rec As DAO.Recordset
' Table1 called "Assets"
Set rec = CurrentDb.OpenRecordset("SELECT * FROM Assets")
If rec.RecordCount > 0 Then
' If the data in List26 matches an Item# in Asset table...
rec.MoveFirst
rec.FindFirst "Item = '" & Me!List26.Value & "'"
If Not rec.NoMatch Then
' Item found.
rec.Edit
' Change Owner field to null
rec!Owner.Value = Null
rec.Update
End If
End If
rec.Close
End Sub
OpenRecordset
采用表/查詢名稱和類型,您需要打開為 dbOpenDynaset 才能使用.findfirst
確保您的列表框設置為使用Bound Column
屬性返回正確的值(默認值可能是記錄的唯一鍵)。
這樣的事情應該這樣做:
Private Sub Check_In_Device_Click()
Dim rec As DAO.Recordset
Set rec = CurrentDb.OpenRecordset("Assets", dbOpenDynaset)
With rec
.FindFirst "[Item] Like '" & List26.Value & "'"
.Edit
![Owner] = ""
.Update
.Close
End With
End Sub
如果要遍歷整個記錄集,可以使用:
Dim rec As DAO.Recordset
Set rec = CurrentDb.OpenRecordset("Assets", dbOpenDynaset)
With rec
.MoveFirst
Do Until .EOF
If ![Item] Like List26.Value Then
.Edit
![Owner].value = Null
.Update
End If
.MoveNext
Loop
.Close
End With
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.