如何通过 VBA 使用 Microsoft Access 中的表单更新 table 上的字段?

How do you update fields on a table using a form in Microsoft Access via VBA?

我有 3 列,标题分别为“已使用”、“添加”和“总计”。 条件是;

已使用:允许用户输入任何正值,但将其作为负值存储在 table 字段中。

添加:允许用户输入正值并将其作为正值存储在 table 字段中。

Total:存储与 Used 和 Add 关联的字段的总和。

这就是我目前所拥有的。提交的总计未按预期工作。有什么想法吗?

'Add to database a new value -------------------------

Private Sub Add_AfterUpdate()

If IsNull(Add.Value) Then
    Add.Value = 0

ElseIf Add.Value < 0 Then
    Add1.Value = -Add.Value

    ElseIf Add.Value > 0 Then
    Add.Value = Add

End If

Total_AfterUpdate 'To update the Total in textbox--------------
Add_Enter 'To show 0 in the textbox--------------


End Sub


'Substract from databae field a new value from already existing value-------


 Private Sub Used_AfterUpdate()

Used.Value = Used
If IsNull(Used.Value) Then
    Used.Value = 0

ElseIf Used.Value < 0 Then
    Used.Value = -Used.Value

    ElseIf Used.Value > 0 Then
    Used.Value = Used

End If


Total_AfterUpdate 'To update the Total in textbox--------------
Add_Enter 'To show 0 in the textbox--------------

End Sub

'Total the results based on changes made through the Used textbox or the Add texbox 

Private Sub Total_AfterUpdate()
Dim TotalAdd As Double
Dim TotalUsed As Double


TotalAdd = Total.Value + Add
Total = TotalAdd
TotalUsed = Total.Value - Used
Total = TotalUsed


End Sub

除非我误解了,请尝试这样的事情:

Private Sub Used_AfterUpdate()
    If IsNull(Used) Then
        Used = 0
    ElseIf Used > 0 Then
        Used = -Used
    End If
    Total_AfterUpdate
End Sub

Private Sub Add_AfterUpdate()
    If IsNull(Add) Then
        Add = 0
    ElseIf Add < 0 Then
        Add = -Add
    End If
    Total_AfterUpdate
End Sub

Private Sub Total_AfterUpdate()
    Total = Used + Add
End Sub

编辑: 或者,可以这样写:

Private Sub Used_AfterUpdate()
    Used = -Abs(Nz(Used, 0))
    Total_AfterUpdate
End Sub

Private Sub Add_AfterUpdate()
    Add = Abs(Nz(Add, 0))
    Total_AfterUpdate
End Sub

Private Sub Total_AfterUpdate()
    Total = Used + Add
End Sub