Home » excel » excel – VBA: How to loop date search for 7 days (day after day)?

excel – VBA: How to loop date search for 7 days (day after day)?

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have written the following code:

Sub bbb()
Dim Cell, cRange As Range: Dim list As Long
Dim test, databse As Workbook: Dim x, y As Worksheet

'open if closed

Set test = Workbooks("test.xlsx")
Set x = test.Sheets(1)

Set database = Workbooks("xxx.xlsm")
Set y = database.Sheets("Data")

list = y.Cells(Rows.Count, "AW").End(xlUp).Row + 1

Set cRange = x.Range("b1:b1200")
For Each Cell In cRange

If Cell.Value = Date - 7 Then
y.Range("AW" & list) = Cell.Offset(0, 1).Value

End If
Next Cell

End Sub

As you can see am pulling the value for TODAY minus 7 days. How can I create a loop to do -7, then -6, -5 ….until -1 ? One value after the other being added to the bottom of the y.Range("AW" & list)

Thanks
West

How to&Answers:

have a go with this one:

Sub bbb()

Application.ScreenUpdating = False: Application.EnableEvents = False

Dim Cell, cRange As Range: Dim list As Long
Dim test, databse As Workbook: Dim x, y As Worksheet
Dim i As Integer

'open if closed <<< I assume you would like to open one (or both) of the workbooks if it's closed?
'if so, the following paragraphs will help:

On Error Resume Next: Set test = Workbooks("empty.csv")
   If Err <> 0 Then Workbooks.Open "C:\empty.csv"
      End If: On Error GoTo 0

On Error Resume Next: Set databse = Workbooks("empty1.csv")
   If Err <> 0 Then: Workbooks.Open "C:\empty1.csv"
      End If: On Error GoTo 0

For i = -7 To -1
         Set test = Workbooks("empty.csv"): Set x = test.Sheets(1)
         Set database = Workbooks("empty1.csv"): Set y = database.Sheets("Data")
         list = y.Cells(Rows.Count, "AW").End(xlUp).Row + 1

Set cRange = x.Range("B1:B1200")
      For Each Cell In cRange
         If Cell.Value = Date + i Then
            y.Range("AW" & list) = Cell.Offset(0, 1).Value
         End If
      Next Cell
Next i

Application.ScreenUpdating = True: Application.EnableEvents = True

End Sub

Answer:

If Cell.Value = Date – 7 Then
y.Range(“AW” & list) = Cell.Offset(0, 1).Value

End If

could change to:

dim dayNumber as integer
for dayNumber = 7 to 1 step -1
   If Cell.Value = Date - dayNumber Then
       y.Range("AW" & list) = Cell.Offset(0, 1).Value
   end if
next