VBA: Find the number of days that occured between dates in records. Example Attached

In the attached worksheet I have two tabs. The first tab is example data I am working with. The second tab is the result I am looking for. The data lives in a MS Access 2016 database.

I worked with a expert on this forum seeking a query solution. However he recommended VBA as a solution.

What I need to do is to loop the sorted table in VBA and then, record by record, find the count of days between each originatordn and the previous record.
Then append the record to a new table.

The goal is to calculate the days since last call for every originatordn.

Example Result:
originatordn      Date      Month      Year      DaysSinceLastCall
2053843380      01-Jan-17      1      2017      0
2053843380      03-Jan-17      1      2017      2
2053843380      05-Jan-17      1      2017      2
2053843380      08-Jan-17      1      2017      3
2053843380      18-Jan-17      1      2017      10
2053843380      28-Jan-17      1      2017      10
Example_DaysSinceLastCall.xlsx
Ryan SimmonsBusiness Analyst IIIAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Rgonzo1971Commented:
Hi,

pls try
Sub macro()
Range("D1").Copy Range("E1")
Range("E1").FormulaR1C1 = "DaysSinceLastCall"
Range("E1").EntireColumn.AutoFit
For Each c In Range(Range("A2"), Range("A" & Rows.Count))
    If c.Offset(-1) = c Then
        c.Offset(, 4) = c.Offset(0, 1) - c.Offset(-1, 1)
    Else
        c.Offset(, 4) = 0
    End If
Next
End Sub

Open in new window

Regards
0
Ryan SimmonsBusiness Analyst IIIAuthor Commented:
That works... ty!
0
Rgonzo1971Commented:
quicker
Sub macro()
Range("D1").Copy Range("E1")
Range("E1").FormulaR1C1 = "DaysSinceLastCall"
Range("E1").EntireColumn.AutoFit
Set Rng = Range(Range("A2"), Range("A" & Rows.Count)).Offset(, 4)
Rng.Formula = "=IF(A2=A1,B2-B1,0)"
Rng.Value = Rng.Value
End Sub

Open in new window

0
Become a Certified Penetration Testing Engineer

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

Fabrice LambertFabrice LambertCommented:
Hi,

I'll suggest a combo of query and VBA solution:
Option Explicit

Public Sub getData()
    Const adOpenStatic As Integer = 3
    
    Dim wb As Excel.Workbook
    Set wb = ThisWorkbook

    Dim cn As Object        '// ADODB.Connection
    Set cn = CreateObject("ADODB.Connection")
    cn.ConnectionString = getConnectionString(wb.FullName)
    cn.Open
    
    Dim SQL As String
    SQL = vbNullString
    SQL = SQL & "SELECT originatordn," & vbCrLf
    SQL = SQL & "       MAX([Date]) AS [Date]," & vbCrLf
    SQL = SQL & "       MAX([Month]) AS [Month]," & vbCrLf
    SQL = SQL & "       MAX([year]) AS [Year]" & vbCrLf
    SQL = SQL & "FROM [Example Data$]" & vbCrLf
    SQL = SQL & "GROUP BY originatordn;"
    
    Dim rs As Object        '// ADODB.Recordset
    Set rs = CreateObject("ADODB.Recordset")
    rs.Open SQL, cn, adOpenStatic
    
    Dim ws As Excel.Worksheet
    Set ws = wb.Worksheets("Example Result")
    copyHeaders rs, ws
    doFormatting ws
    
    Dim rng As Excel.Range
    Set rng = ws.Range("A2")
    rng.CopyFromRecordset rs
    
    rs.Close
    Set rs = Nothing
    cn.Close
    Set cn = Nothing
    
    computedays ws
    Set ws = Nothing
    Set wb = Nothing
End Sub

Private Function getConnectionString(ByVal path As String) As String
    getConnectionString = vbNullString
    getConnectionString = getConnectionString & "Provider=Microsoft.ACE.OLEDB.12.0;"
    getConnectionString = getConnectionString & "Data Source=" & path & ";"
    getConnectionString = getConnectionString & "Extended Properties=""Excel 12.0 Macro;HDR=YES"";"
End Function

Private Sub copyHeaders(ByRef rs As ADODB.Recordset, ByRef ws As Excel.Worksheet)
    Dim rng As Excel.Range
    Set rng = ws.Range("A1")
    
    Dim field As ADODB.field
    For Each field In rs.Fields
        rng.Value = field.Name
        Set rng = rng.Offset(columnoffset:=1)
    Next
    rng.Value = "DaysSinceLastCall"
    Set rng = Nothing
End Sub

Private Sub computedays(ByRef ws As Excel.Worksheet)
    Dim rng As Excel.Range
    
    Set rng = ws.Range("D2")
    While rng.Value
        rng.Offset(columnoffset:=1).FormulaR1C1 = "=DAYS(NOW(),RC[-3])"
        Set rng = rng.Offset(rowoffset:=1)
    Wend
    Set rng = Nothing
End Sub

Private Function doFormatting(ByRef ws As Excel.Worksheet)
    Dim rng As Excel.Range
    Set rng = ws.Range("B:B")
    
    rng.NumberFormat = "m/d/yyyy"
    Set rng = Nothing
End Function

Open in new window

PS: I wrote this within a workbook, it is easilly transferable to Ms Access.
don't forget to late bind excel library.
0
OMC2000Commented:
If you have your data in MS Access you could get the expected result with a simple SQL query

SELECT t1.Originator, t1.sDate,
t1.sDate -
IIf( IsNull((select max (t2.sDate) from t1 as t2 where t1.Originator = t2.Originator and t2.sDate < t1.sDate)),
t1.sDate, t1.Month, t1.Year
(select max (t2.sDate) from t1 as t2 where t1.Originator = t2.Originator and t2.sDate < t1.sDate)
) as DaysSinceLastCall
FROM t1 as t1
;
0
Rgonzo1971Commented:
Corrected code
Sub macro()
Range("D1").Copy Range("E1")
Range("E1").FormulaR1C1 = "DaysSinceLastCall"
Range("E1").EntireColumn.AutoFit
Set Rng = Range(Range("A2"), Range("A" & Rows.Count).End(xlUp)).Offset(, 4)
Rng.Formula = "=IF(A2=A1,B2-B1,0)"
Rng.Value = Rng.Value
End Sub

Open in new window

0
Fabrice LambertFabrice LambertCommented:
scratch my answer, missed Something.
0
LearnReporting Automation ExpertCommented:
Hi
Please find attached Macro file, this will get you the exact output what your expecting, using very simple coding

Just open the file past your data in Example Data sheet and click run button, coding not protected you can open and change it if you want.

Thanks and please let me know!

Thanks and Regards,

Learn Excel in Tamil
Mail us: learnexcelintamil@gmail.com
Subscribe on YouTube : https://www.youtube.com/channel/UC5vGAvycUz41AzyUP7vi61Q
Like our page in Facebook : https://www.facebook.com/Learnexcelintamil/
Example_DaysSinceLastCall.xlsm
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
VBA

From novice to tech pro — start learning today.