Share via

How to loop through cell ranges calculating datediff

Anonymous
2014-10-15T19:45:37+00:00

I have a question on regard to calculating date difference in days, looping through a cell range. This is the code that I have come up with but it only calculates for the first record on the spreadsheet. Im totally missing the looping function to go through each of the rows.

I have created a button on the spreadsheet that when clicked it references the below macro. 

Please help.

Sub Test2()

      ' Select cell A2, *first line of data*.

      Range("A2").Select

      Dim ws As Worksheet

     Dim date1 As Range

    Dim date2 As Range

    Dim x As String ' this is the dates calculation value

    Dim destcell As Range 'destination cell

      ' Set Do loop to stop when an empty cell is reached.

      Do Until IsEmpty(ActiveCell)

         Set destcell = Worksheets("G0").Range("$AW2") 'initiate destination cell

         Set date1 = Worksheets("G0").Range("$AB2") ' initiate cell range for first date to use for calculation

         Set date2 = Worksheets("G0").Range("$A2") ' initiate cell range for second date to use for calculation

         'For next here??

         x = DateDiff("d", date1, date2) ' calculation to assign date difference in days to variable x

         destcell.Value = x  'copy contents of variable into specified cell range

        ' Step down 1 row from present location.

         ActiveCell.Offset(1, 0).Select

         'Need to enter loop here

      Loop

   End Sub

Microsoft 365 and Office | Excel | For home | Windows

Locked Question. This question was migrated from the Microsoft Support Community. You can vote on whether it's helpful, but you can't add comments or replies or follow the question.

0 comments No comments

Answer accepted by question author

HansV 462.6K Reputation points
2014-10-15T20:16:13+00:00

Try this version:

Sub Test2()

    Dim ws As Worksheet

    Dim r As Long

    Dim m As Long

    Set ws = Worksheets("G0")

    m = ws.Range("A" & ws.Rows.Count).End(xlUp).Row

    Application.ScreenUpdating = False

    For r = 2 To m

        ws.Range("AW" & r).Value = DateDiff("d", ws.Range("AB" & r).Value, ws.Range("A" & r).Value)

    Next r

    Application.ScreenUpdating = True

End Sub

Was this answer helpful?

0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Anonymous
    2014-10-15T20:35:56+00:00

    This worked beautifully! Thanks so much for your help.

    Was this answer helpful?

    0 comments No comments
  2. Anonymous
    2014-10-15T20:35:52+00:00

    No need to loop at all:

    Sub Test2()

        Dim lRow As Long

        With Worksheets("G0")

            lRow = .Cells(.Rows.Count, "A").End(xlUp).Row

            With .Range("AW2:AW" & lRow)

                .Formula = "=DateDif(AB2,A2,""d"")"

                .Value = .Value

            End With

        End With

    End Sub

    Was this answer helpful?

    0 comments No comments