首页 > 解决方案 > 使用两个表中的类似字段在 MS VBA 中运行 IF 语句

问题描述

我正在尝试根据当前数量的总和设置数量值,然后根据另一个表中的数量值减去一个数量。我目前的思考过程是:如果 QuantityA 小于或等于 Quantity B,则从 Quantity B 中减去 QuantityA。我不是 SQL 和 MS VBA 专家,所以我想知道如何使用两个不同的表创建 if 语句。

Private Sub Command23_Click()

    If QuantityA <= QuantityB Then
        QuantityB = QuantityB - QuantityA

    Else
       MsgBox "You can not hire that many" & ToolName & "as there is only" & [DEPARTMENT TOOLS (stocked)].Quantity & "available"

    End If
        MsgBox "Your hire request has been successful"
End Sub

任何帮助,将不胜感激

标签: vbams-access

解决方案


您可以通过打开包含查询结果的记录集并比较查询返回的值来实现您的要求。为了将查询限制为适当的数量,您需要传入您正在检查的工具的 ID。

@June7 关于保存计算数据是正确的。您唯一想要保存它的时间是您保留事件日志或连接查询的速度是否成为问题(不太可能给出正确的数据库结构)

toolId might be stored in a text box control for example
Function Something_Click(toolId as string)
  Dim rs as Recordset
  ' create a recordset containing data from the two tables
  Set rs = CurrentDB.OpenRecordset("SELECT A.TOOL_QTY AS TOOL_QTY_A, " _
           & " B.TOOL_QTY AS TOOL_QTY_B, A.TOOLNAME AS TOOLNAME" _
           & " FROM TABLE1 AS A  " _
           & " INNER JOIN TABLE2 AS B ON A.TOOL_ID = B.TOOL_ID" _ 
           & " WHERE A.TOOL_ID = '" & toolId & "'")
  ' compare the values in the table
  If rs![TOOL_QTY_A] <= rs![TOOL_QTY_B] Then
    ' your true condition, for example
    ' MsgBox "Success"
  Else
    ' your false condition, for example
    ' MsgBox "Oops, not enough of " & rs![TOOLNAME]
  End If
  ' close the recordset
  rs.close
End Function

推荐阅读