【发布时间】:2019-01-07 19:57:45
【问题描述】:
我正在尝试制作一个 MS Access 应用程序,它对 VBA 来说相当新,但习惯于 MySQL。我遇到的问题是我试图向表中插入值,代码运行时没有给出错误,但表没有更新。有人可以帮忙吗?
我主要对这一行有疑问:
db.Execute ("INSERT INTO Transaction ([TranDate], TranItem365, TranAmount, TranOperation) VALUES ( #" & Now() & "# , " & txtTranItem365.Value & ", " & txtTranAmount.Value & ", '" & txtTranOperation.Value & "')")
这是上下文的完整代码。
Private Sub btnApplyTransaction_Click()
Dim db As Database
Dim sql As String
Dim oper As String
Set db = CurrentDb()
If txtTranItem365.ListIndex = -1 Then
MsgBox "Please select an item.", vbCritical
ElseIf txtTranAmount.Value = "" Then
MsgBox "Please enter an amount.", vbCritical
ElseIf txtTranOperation.Value = "Issue" And txtIssuedToDept.ListIndex = -1 Then
MsgBox "Please select a department to issue to.", vbCritical
Else:
sql = DLookup("[ItmStock]", "Items", "[Itm365]=" & txtTranItem365.Value)
oper = "+"
If txtTranOperation.Value = "Issue" Then
oper = "-"
End If
db.Execute ("Update Items set ItmStock = (" & sql & oper & txtTranAmount & ") where Itm365=" & txtTranItem365.Value)
db.Execute ("INSERT INTO Transaction ([TranDate], TranItem365, TranAmount, TranOperation) VALUES ( #" & Now() & "# , " & txtTranItem365.Value & ", " & txtTranAmount.Value & ", '" & txtTranOperation.Value & "')")
If txtTranOperation.Value = "Issue" Then
sql = "32"
MsgBox "INSERT INTO Issueance values (" & sql & ", " & txtIssuedToDept.Value & ", " & txtIssuedTo.Value & ")"
db.Execute ("INSERT INTO Issueance values (" & sql & ", " & txtIssuedToDept.Value & ", '" & txtIssuedTo.Value & "')")
End If
txtTranAmount.Value = ""
txtTranItem365 = ""
txtTranOperation = "Add"
txtIssuedTo = ""
txtIssuedToDept = ""
DoCmd.RefreshRecord
db.Close
End If
更多上下文: TranDate 是日期+时间,本质是 Now() 函数。 TranItem365 是一个数字。 TranAmount 是一个数字。 TranOperation 是 ["Add", "Issue"]。
【问题讨论】:
-
一切正常。可以尝试的东西很少。尝试通过更改
dim db as DAO.Database使您的数据库显式 DAO。此外,Access 有时会对字段名称挑剔。为确保这不是问题,请用[]将所有字段括起来。如果您尝试在新的查询窗口中使用 Access 手动运行此插入,会发生什么情况? -
以@RyanWildry 为基础:将该查询放入字符串变量中。设置断点,获取字符串内容的副本,然后尝试在查询窗口中运行查询。你应该得到一些诊断。
-
更新,尝试 [],没有帮助。尝试在查询窗口中运行它实际上给出了一个提示,“由于键违规,没有添加 1 条记录”
-
你去!干得好。
-
第二个 INSERT 语法无效。所以一旦你通过了第一个,就会有另一个错误。表“问题”名称拼写错误,但我认为这是实际的表名。