我正在制作一个相当简单的库存跟踪数据库。我想通过 ID 检索记录,并在金额中添加或删除指定的数字。如果它不存在,我想添加它。甚至可以在不绑定到表的情况下执行此操作吗?
问问题
18210 次
2 回答
1
听起来你有一个候选ID
值。也许它包含在一个名为MyID
. 并且您还有另一个数值MyAmtChange
,它将添加到表中为字段值匹配amount
的行命名的字段中的值中。 ID
MyID
一个复杂的问题是您的表中可能没有ID
值匹配的行MyID
。在这种情况下,您需要为其添加一行。
如果那是正确的,当一个不存在时,INSERT
一行。MyID
然后你可以简单地UPDATE
在amount
匹配的行中MyID
。
Dim strInsert As String
Dim strUpdate As String
Dim db As DAO.Database
Set db = CurrentDb
If DCount("*", "YourTableNameHere", "ID = " & MyID) = 0 Then
strInsert = "INSERT INTO YourTableNameHere (ID)" & vbCrLf & _
"VALUES (" & MyID & ");"
Debug.Print strInsert
db.Execute strInsert, dbFailOnError
End If
strUpdate = "UPDATE YourTableNameHere" & vbCrLf & _
"SET amount = Nz(amount, 0) + " & MyAmtChange & vbCrLf & _
"WHERE ID = " & MyID & ";"
Debug.Print strUpdate
db.Execute strUpdate, dbFailOnError
Set db = Nothing
如果这个猜测相当接近,则向该代码添加一个错误处理程序块,以处理dbFailOnError
... 或任何其他错误出现的任何问题。
于 2012-10-07T19:38:38.760 回答
1
我不知道你到底想要什么,但这段代码展示了如何使用 VB-Access 操作数据。
Sub fnStudent()
On Error GoTo insertError
Dim studentQuery As String
'INSERTING INTO TABLE
studentQuery = "INSERT INTO Students values ('10','YAHYA','02/10/2012')"
CurrentDb.Execute studentQuery, dbFailOnError
'UPDATING
studentQuery = "UPDATE Students Set name='YAHYA OULD ABBA' WHERE stdID='10'"
CurrentDb.Execute studentQuery, dbFailOnError
'LISTING VALUES
Dim studentsRS As Recordset
Set studentsRS = CurrentDb.OpenRecordset("SELECT * FROM Students WHERE upper(name) like '%YAHYA%';")
Do While Not studentsRS.EOF
MsgBox "ID : " & studentsRS.Fields(0) & "Name : " & studentsRS.Fields(1) & "Birth Date : " & studentsRS.Fields(2)
studentsRS.MoveNext
Loop
'DELETING
studentQuery = "DELETE FROM Students WHERE stdID='10'"
CurrentDb.Execute studentQuery, dbFailOnError
Exit Sub 'exit if there was no error
'UPDATE:
errorHandler:
If Err.Number = 3022 Then
MsgBox "Can't have duplicate key; index changes were unsuccessful", vbMsgBoxRtlReading + vbCritical, "Error " & Err.Number
Else : MsgBox "Error" & vbCrLf & Err.Description, vbMsgBoxRtlReading + vbCritical, "Error " & Err.Number
End If
End Sub
在这里您可以找到vba
错误列表http://www.halfile.com/vb.html
于 2012-10-02T12:28:57.680 回答