gpt-3.5-turbo-0125· OpenAI
WildChat-4.8M (AI2)
This formula is not finding the right dates. I am trying to get dates that are 7 days…
- User
This formula is not finding the right dates. I am trying to get dates that are 7 days from today: Sub ServiceIn7()
code' Unlock Sheet Me.Unprotect Password:="edit" ' Declare variables with descriptive names Dim ws As Worksheet Dim rng As Range Dim serviceStartDate As Date ' More descriptive name Dim serviceEndDate As Date Dim serviceDueFilePath As String ' More descriptive name Dim serviceLine As String ' Set variables Set ws = Sheets("Service Schedules") serviceStartDate = DateSerial(Year(Now), Month(Now), Day(Now) - 7) ' Changed to 7 days serviceEndDate = DateSerial(Year(Now), Month(Now), Day(Now) + 7) serviceDueFilePath = ThisWorkbook.Path & "\zzzz ServProvDocs\ServiceDue.txt" ' Assuming same file ' Open the text file for overwriting (or change to Append As #1 if needed) Open serviceDueFilePath For Output As #1 Print #1, "" ' Clear the file Close #1 ' Loop through the dates in column Z For Each rng In ws.Range("Z:Z") If rng.Value >= serviceStartDate And rng.Value <= serviceEndDate Then ' Build the service line with proper formatting serviceLine = rng.Value & vbCrLf & _ ws.Range("J" & rng.row).Value & vbCrLf & _ ws.Range("K" & rng.row).Value & vbCrLf & vbCrLf ' Open the file in append mode and write the line Open serviceDueFilePath For Append As #1 Print #1, Replace(Replace(serviceLine, vbCrLf, " "), vbTab, " ") & vbCrLf Close #1 End If Next rng ' Open the text file with notepad (optional) Application.DisplayAlerts = False Shell "notepad " & serviceDueFilePath, vbNormalFocus Application.DisplayAlerts = True ' Lock Sheet Me.Protect Password:="edit" - Assistant
The issue with the formula is in the calculation of the serviceStartDate and serviceEndDate. Instead of subtracting and adding 7 days to the current date, you should use the DateAdd function to add or subtract a specific number of days to the current date.
Here is the updated code with the correct calculation:
VBA