在ms访问中获取值第一行到第二行(表)

时间:2017-11-21 09:17:19

标签: vba ms-access access-vba

我创建了一个包含Part In和Part Out的备用列表。如下图所示。

enter image description here

如您所见,有零件,零件和库存余额。当我输入Part In值= 1时,Stock balance值等于1,当我输入Part Out值时,它将扣除库存余额值。问题是如何从第1行捕获库存余额值到第2行?输入新值时的想法Part In:

[Stock Balance row 2 = Stock Balance from row 1 + Part In]

我希望你理解我的解释并帮助我。谢谢。

1 个答案:

答案 0 :(得分:0)

由于评论时间过长,我会将此作为回答我的评论的补充

  

表格中有三个字段可能更好 - 日期/时间   交易,交易方向(进出)和零件数量   在交易中。然后,您可以添加所有零件,减去所有零件   在任何时间点取出并取得平衡

运行以下VBA以创建包含三个字段的表并添加一些示例数据:

Sub Test()

    With DoCmd

        .SetWarnings False

        .RunSQL "CREATE TABLE Stock (" & _
            "Date_Time DateTime, Direction CHAR, Unit INTEGER)"

        .RunSQL "INSERT INTO Stock VALUES(#2017/11/20 07:00:00#, 'In', 100)"
        .RunSQL "INSERT INTO Stock VALUES(#2017/11/20 07:00:01#, 'Out', 5)"
        .RunSQL "INSERT INTO Stock VALUES( #2017/11/20 07:00:02#, 'In', 3)"
        .RunSQL "INSERT INTO Stock VALUES(#2017/11/20 07:00:05#, 'In', 2)"
        .RunSQL "INSERT INTO Stock VALUES(#2017/11/20 07:10:00#, 'Out', 15)"

        .SetWarnings True

    End With

End Sub  

此SQL将为您提供余额的运行总计:

SELECT        T1.Date_Time
            , T1.Direction
            , T1.Unit
            , (
               SELECT   SUM(Unit)
               FROM     Stock
               WHERE    Direction='IN' AND Date_Time<=T1.Date_Time
               ) -
              NZ((
               SELECT   SUM(Unit)
               FROM     Stock
               WHERE    Direction='OUT' AND Date_Time<=T1.Date_Time
               ),0) AS Balance
FROM        Stock T1

此SQL将在特定时间点给出平衡:

SELECT      Date_Time AS TimeFrame
            , (
            SELECT  SUM(Unit) AS Stock_In
            FROM    Stock
            WHERE   Direction='In' AND Date_Time<=#2017/11/20  07:00:05#
              )  - 
            (
            SELECT  SUM(Unit) AS Stock_Out
            FROM    Stock
            WHERE   Direction='Out' AND Date_Time<=#2017/11/20  07:00:05#
            ) AS Balance
FROM        Stock
WHERE       Date_Time=#2017/11/20 07:00:05#