excelvba

Compare vba .Now vs cell Today formula


I have a script that timestamp whenever I put data, but sometimes I have to change the date manually. The problem is when I have to apply a formula between these 2, the automatic timestamp and the manual date, for example "if is the same date", it return false value for the same date, even when it is in the same format. I know it is something with the script set as "as string" but I don't know how to fix it
I need to do for example:
=IF(J2=TODAY();1;0)
"J2" is the automatic timestamp with .Now by the following script

Private Sub Worksheet_Change(ByVal Target As Range)
  Const ColumnsToMonitor As String = "k:z"
  Const DateColumn As String = "j"
  Application.EnableEvents = True
  
  
  If Not Intersect(Target, Columns(ColumnsToMonitor)) Is Nothing Then
    Intersect(Target.EntireRow, Columns(DateColumn)).Value = Format(Now, "ddd d/mm")
  End If
       
  Application.EnableEvents = True
End Sub

how to fix the script so I can compare the automatic timestamp with =Now to a manual date or =Today formula


Solution

  • The following code line populates cells in column J with text (String) instead of a date/value. As a result, J2=TODAY() evaluates to False. A quick fix is to update the formula to =IF(J2=TEXT(TODAY(), "ddd d/mm"),1,0).

    Intersect(Target.EntireRow, Columns(DateColumn)).Value = Format(Now, "ddd d/mm")
    

    I recommend updating your script to populate the cells in column J with actual dates. Here are the suggested changes:

    Your formulas should work correctly after applying the changes.

    Private Sub Worksheet_Change(ByVal Target As Range)
      Const ColumnsToMonitor As String = "k:z"
      Const DateColumn As String = "j"
      Application.EnableEvents = False
      
      If Not Intersect(Target, Columns(ColumnsToMonitor)) Is Nothing Then
            With Intersect(Target.EntireRow, Columns(DateColumn))
                .Value = Date
                .NumberFormat = "ddd d/mm"
            End With
      End If
           
      Application.EnableEvents = True
    End Sub