PDA

View Full Version : subtract today's date from a date in another column



elsuji
12-23-2019, 10:14 AM
Dear Team,

I am having dates in Worksheet Sheet1 column D. I want to subtract Todays date from a date in column D and update on Column L.

For that i am trying the following code. But it is not working


Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim LastRow As Long, i As Long
With Worksheets("Sheet1")
LastRow = .Cells(.Rows.Count, "D").End(xlUp).Row
For i = 2 To LastRow
.Range("L" & i).Value = Date - Range("D" & i).Value
Next i
End With
End Sub




Can any one tell me what is the mistake on above code

Bob Phillips
12-23-2019, 11:10 AM
Private Sub Worksheet_Change(ByVal Target As Range)

If Target.Column <> 4 Then Exit Sub

With Me.Cells(Target.Row, "L")

.Value = Date - Target.Value
.NumberFormat = "General"
End With
End Sub

elsuji
12-23-2019, 11:37 AM
Dear XLD,

Thanks for your reply.

When is trying to upload my datas and using the above your code i am getting "Type Mismatch" error.

I attached my files here for your kind reference.

Kindly check and update

SamT
12-23-2019, 07:27 PM
Can any one tell me what is the mistake on above code
Probably the missing Dot before Range. Try this

.Cells(i, "L") = DateDiff("d", Date, CDate(.Range("D" & i)))

Paul_Hossler
12-23-2019, 08:16 PM
Little more elaborate



Option Explicit


Private Sub Worksheet_Change(ByVal Target As Range)
Dim r As Range


Application.EnableEvents = False


For Each r In Intersect(Target, Me.UsedRange).Cells
With r
If .Column <> 4 Then GoTo NextCell
If Not IsDate(.Value) Then GoTo NextCell


.Offset(0, 8).Value = Date - .Value
.Offset(0, 8).NumberFormat = Application.International(xlGeneralFormatName)
End With
NextCell:
Next


Application.EnableEvents = True
End Sub

avichandana
01-21-2020, 02:45 AM
i have written

=Today() in cell A1.
anydate in cell B1
Then A1-B1 in cell C1 and changed it to datatype General