简体   繁体   中英

How can I write this cell-referenced Excel formula in VBA to use in MS Access: (b2-a1)

This is a very simple calculation to do in Excel but I am stumped on how to do this within Access using 2 fields in a table in different records. One application I have needs to find the difference between an operation STOPTime and the next STARTTime. Any help will be greatly appreciated. I am new to VBA.

Sub samPle()
Dim startTime As Date
Dim endTime As Date

startTime = Time
'''Your Code


endTime = Time

Debug.Print DateDiff("n", startTime, endTime) ' difference in minutes

End Sub

There are a number of ways to approach the problem depending in your data, which makes posting data for questions about SQL very important. For example:

Table:

ID  EventTime           EventType
1   17/02/2013 08:52:00 start
2   17/02/2013 09:52:00 stop
3   17/02/2013 11:52:00 start
4   17/02/2013 15:52:00 stop

SQL:

SELECT a.id,
       a.eventtime                    AS Start,
       a.eventtype,
       (SELECT TOP 1 eventtime
        FROM   times b
        WHERE  eventtype = "stop"
               AND eventtime > a.eventtime
        ORDER  BY eventtime,
                  id)                 AS Stop,
       Datediff("n", [start], [stop]) AS RunTime
FROM   times AS a
WHERE  (( ( a.eventtype ) = "start" ))
ORDER  BY a.eventtime;

Result:

ID  Start               EventType   Stop                RunTime
1   17/02/2013 08:52:00 start       17/02/2013 09:52:00     60
3   17/02/2013 11:52:00 start       17/02/2013 15:52:00     240

Re comment

SELECT a.id, 
       a.eventtime                         AS Start, 
       a.eventtype, 
       (SELECT TOP 1 eventtime 
        FROM   times b 
        WHERE  eventtype = "stop" 
               AND eventtime > a.eventtime 
        ORDER  BY eventtime, 
                  id)                      AS Stop, 
       Datediff("n", [start], [stop])      AS RunTime, 
       (SELECT TOP 1 eventtime 
        FROM   times b 
        WHERE  eventtype = "start" 
               AND eventtime > a.eventtime 
        ORDER  BY eventtime, 
                  id)                      AS NextStart, 
       Datediff("n", [start], [nextstart]) AS StartDiff, 
       Datediff("n", [stop], [nextstart])  AS DownTime 
FROM   times AS a 
WHERE  (( ( a.eventtype ) = "start" )) 
ORDER  BY a.eventtime; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM