Delete date that falls outside of inputted month - excel

I'm creating a sub that formats a new time sheet. I need it to delete dates that fall outside of the inputted month (in this case, June, 2020). The code autofills the next 30 days after the first day, which covers the maximum days in a month (31 days), but also adds date for the first day(s) in the next month if the inputted month has less than 31 days. Here is my code:
Sub Calendar_Genorator3()
Dim WS As Worksheet
Dim MyInput As Variant
Dim StartDay As Variant
Dim DayofWeek As Variant
Dim CurYear As Variant
Dim CurMonth As Variant
Dim FinalDay As Variant
Dim Cell As Range
Dim RowCell As Long
Dim ColCell As Long
Dim Day1 As Range
Set WS = ActiveWorkbook.ActiveSheet
WS.Range("A1:R100").Clear
MyInput = InputBox("Type in Month and year for Calendar ")
If MyInput = "" Then Exit Sub
' Get the date value of the beginning of inputted month.
StartDay = DateValue(MyInput)
' Check if valid date but not the first of the month
' -- if so, reset StartDay to first day of month.
If Day(StartDay) <> 1 Then
StartDay = DateValue(Month(StartDay) & "/1/" & _
Year(StartDay))
End If
'Set headers
Range("a1").Value = Application.Text(MyInput, "mmmm") & " Time Sheet"
Range("a2") = "Day"
Range("c2") = "Time In"
Range("d2") = "Time Out"
Range("e2") = "Hours"
Range("f2") = "Notes"
Range("g2") = "Overtime"
'Set weekdays
Range("a3") = "Sunday"
Range("a4") = "Monday"
Range("a5") = "Tuesday"
Range("a6") = "Wednesday"
Range("a7") = "Thursday"
Range("a8") = "Friday"
Range("a9") = "Saturday"
DayofWeek = Weekday(StartDay)
' Set variables to identify the year and month as separate variables.
CurYear = Year(StartDay)
CurMonth = Month(StartDay)
' Set variable and calculate the first day of the next month.
FinalDay = DateSerial(CurYear, CurMonth + 1, 1)
' Place a "1" in cell position of the first day of the chosen month based on DayofWeek.
Select Case DayofWeek
Case 1
Range("b3").Value = 1
Case 2
Range("b4").Value = 1
Case 3
Range("b5").Value = 1
Case 4
Range("b6").Value = 1
Case 5
Range("b7").Value = 1
Case 6
Range("b8").Value = 1
Case 7
Range("b9").Value = 1
End Select
'Loop through range b3:b44 incrementing each cell after the "1" cell.
For Each Cell In Range("b3:b44")
RowCell = Cell.Row
ColCell = Cell.Column
'Do if "1" is in column B or 2.
If Cell.Row = 1 And Cell.Column = 2 Then
' Do if current cell is not in 1st column.
ElseIf Cell.Row <> 1 Then
If Cell.Offset(-1, 0).Value >= 1 Then
Cell.Value = Cell.Offset(-1, 0).Value + 1
' Stop when the last day of the month has been entered.
If Cell.Value > (FinalDay - StartDay) Then
Cell.Value = ""
' Exit loop when calendar has correct number of days shown.
Exit For
End If
End If
End If
Next
For Each Cell In Range("b3:b9")
If Cell.Value = "" Then
Cell.EntireRow.Clear
End If
Next
'Clears rows without dates
For Each Cell In Range("b3:b9")
If Cell.Value = "" Then
Cell.EntireRow.Delete
End If
Next
'Deletes top rows without dates; needs a loop to successfully delete all empty rows
Range("b2") = "Date"
'Added "Date" in later so date insert works
Set Day1 = WS.Cells.Find(What:="1", LookIn:=xlValues, _
lookat:=xlWhole, searchorder:=xlByColumns, searchdirection:=xlNext, _
MatchCase:=True, SearchFormat:=False)
'Find start day, which is day 1
If Not Day1 Is Nothing Then
Day1.Value = Application.Text(MyInput, "mmm-d")
End If
With Day1
Day1.AutoFill Destination:=Range("B3:B33"), Type:=xlFillDefault
End With
'These final lines of code don't delete ranges with dates that fall outside of the inputted month, because FinalDay doesn't refer to the last day of the month. I need to come up with something that refers to the last day of the month.
FinalDay.Select
With Selection
Cell.Offset(-1).End(xlDown).EntireRow.Delete
End With
End Sub
Here's the output of this code. Any ideas on how to delete the rows that have dates that fall outside of the inputted month? I'm also open to writing this sub an entirely different way; I did it this way because I'm basing it on MS template code.

Yours is a very nice effort. With the code below I have taken a different approach. I hope you will like to study it. I've added lots of comments.
Sub Calendar_Generator()
' 046
Dim Ws As Worksheet
Dim MyInput As String ' InputBox generates a string
Dim StartDay As Date ' this must be date
Dim Sp() As String ' working array
Dim i As Integer ' looping index
Dim R As Long ' row counter
Set Ws = ActiveWorkbook.ActiveSheet ' not a good idea. Always specify the tab by name!
Ws.Range("A1:R100").Clear
Do
MyInput = InputBox("Enter the start date for the Calendar:")
If MyInput = "" Then Exit Sub
Loop While Not IsDate(MyInput) ' repeat if entry isn't recognized as a date
' Set the date value of the beginning of inputted month.
' -- regardless of the day the user entered, even if missing
StartDay = DateSerial(Year(CDate(MyInput)), Month(CDate(MyInput)), 1)
'Set headers
Range("a1").Value = Format(StartDay, "mmmm") & " Time Sheet"
Sp = Split("Day,Date,Time In,Time Out,Hours,Notes,Overtime", ",")
For i = 0 To UBound(Sp)
Ws.Cells(2, 1 + i).Value = Sp(i) ' always specify the worksheet
Next i
' fill the days for the selected month
' == the last day of a month is always the day before the first of the next
' here deducting 2 to count from 0
For R = 0 To Day(DateAdd("m", 1, StartDay) - 2)
With Ws.Cells(3 + R, 2)
.Value = StartDay + R
.NumberFormat = "d-mmm"
.Offset(, -1).Value = StartDay + R
.Offset(, -1).NumberFormat = "dddd"
End With
Next R
End Sub
If you look at the declarations, four out of six - two thirds of their total - are used for code management. That shows where my focus was, and the result is shorter, more efficient code. Much of this was achieved by following a simple rule (which the macro recorder doesn't seem to know): Use cell addressing syntax for addressing cells and range addressing syntax only for addressing ranges of cells. Cell coordinates are easy to calculate and use in loops.

Related

How to Test if a Date Falls within a Certain Range and Copy the Entire Row if So Using VBA

I have a file tjhat is serving as a log of product expirations. We track it by two dates, the date as provided by the manufacturer as well as the "Effective Expiration Date". The latter is the date in which the product would expire before someone could use it as directed.
Each year is a separate Worksheet (2022, 2023, 2024, etc.) with a table named after it (_2022, _2023, etc.).
We would like to create a Macro that will go through the the current year's table as well as the one for the next two years searching for a date that falls within the range of today's date through a week later. If it finds a match, the row should be copied over to a new sheet called "Weekly Exp" that is created by the Macro.
So if I ran it today, 12/17/2022, it will search for anything with an Effective Expiration Date between 12/17/2022 and 12/24/2022.
Here is what I have so far:
Sub weeklyExpirationSheet()
Dim dtToday As Date
Dim dtWeekOut As Date
Dim dtEffExp As Date
Dim dtTest As Date
Dim theYear As String
Dim countDays As Long
Dim ws As Worksheet
Dim srcSheet As Worksheet
Dim destSheet As Worksheet
Dim srcTable As ListObject
Dim srcRow As Range
dtToday = Date
dtWeekOut = DateAdd("ww", 1, dtToday)
countDays = DateDiff("d", dtToday, dtWeekOut)
For Each ws In ActiveWorkbook.Worksheets
If ws.Name = "Weekly Exp" Then
MsgBox "Weekly Audit Sheet Already Exists!"
Exit Sub
End If
Next ws
Sheets.Add(After:=Sheets("Incoming")).Name = "Weekly Exp"
Set destSheet = Worksheets("Weekly Exp")
With destSheet
Range("A1").Value = "UPC"
Range("B1").Value = "Brand"
Range("C1").Value = "Product"
Range("D1").Value = "Sz"
Range("E1").Value = "Expr"
Range("F1").Value = "Eff Exp"
Range("G1").Value = "Qty"
Range("H1").Value = "Location"
dtCurrentYear = CDbl(Year(Date))
dtEndYear = CDbl(dtCurrentYear + 2)
For y = dtCurrentYear To dtEndYear
Set srcSheet = Worksheets(CStr(y))
Set srcTable = srcSheet.ListObjects("_" & CStr(y))
With srcSheet
LastRow = .Cells(Rows.Count, "A").End(xlUp).Row
For p = 2 To LastRow
dtTest = .Cells(p, "F").Value
If dtTest >= dtToday And dtTest <= dtWeekOut Then
destLastRow = destSheet.Cells(Rows.Count, "A").End(xlUp).Row + 1
Rows(p).Copy Destination:=destSheet.Rows(destLastRow)
End If
Next p
End With
Next y
End With
End Sub
The code for getting the dates and such is working as is the detection/creation of the Worksheet. However when I run the Macro, it runs for a long period of time (like 3-5min) and then gives a Type Mismatch error. Nothing gets copied.
I did replace the copying code with MsgBox that would just display matches, it was going beyond the range. It reported an item that had a date of 12/31/2022 for example.
Edit:
This is what the data looks like
Your condition is missing the And operator so it always evaluates to True,
Write it like this:
If dtTest >= dtToday And dtTest <= dtWeekOut Then

VBA Error 91 , after calling Sub within the main Sub

I have a VBA Module that is trying to get all occurrences of a date in column G in one sheet. After finding the row of the occurrence, I'm saving other values from the sheet on the same row from different columns, i.e. bldg, and room, and numPerson.
What I'm trying to do after that is to get the call a function with the date, numPerson, bldg and room as arguments. The function FillDateCapacitiesInOccupancySheet should go to a different sheet and search column B for the bldg, get that row, then look for the room on the same row and place the numPpl on the row under the correct column for the date that was given. In the following code I get an Error 91 on the Loop While statement if I remove
If FoundCell Is Nothing Then
MsgBox "No Found Cell Address", vbInformation
Exit Sub
End If
The click function works fine if I remove the call to the function FillDateCapacitiesInOccupancySheet, but otherwise I get an error. Either the FoundCell or myRange is empty but I'm not sure why or how to fix it.
Sub ConflictButton_Click()
Dim sourceColumn As Range
Dim targetColumn As Range
Dim beginningDate As String, stringDate As String, month As String, day As String, year As String
Dim dates As Date
Dim occWS As Worksheet, excepWS As Worksheet
Dim beginningDateCell As Range, addDatesCells As Range, FindDateRow As Range
Dim datesArray(1 To 7) As Date, stringDatesArray(1 To 7) As String
Dim lLoop As Long, findRowNumber As Long
Dim tempMonth As String, tempDay As String
Dim fnd As String, FirstFound As String
Dim FoundCell As Range, rng As Range
Dim myRange As Range, LastCell As Range
'Copy Building, Room, and Max Capacity Columns from sheet Table to sheet OccupancyByDate
Set sourceColumn = ThisWorkbook.Worksheets("Table").Columns("B:D").Rows("3:500")
Set targetColumn = ThisWorkbook.Worksheets("OccupancyByDate").Columns("B:D").Rows("3:500")
sourceColumn.Copy Destination:=targetColumn
'open FindConflictDates Form
FindConflictDatesForm.Show
'Set OccupancyByDate sheet Column E Row 2 (Column Header) to the Week Starting Date,
'get the week beginning string from what was saved from the FindConflictDatesForm
If WeekBeginningString <> "" Then
beginningDate = WeekBeginningString
WeekBeginningDate = CDate(beginningDate) ' convert String to Date
Set occWS = ThisWorkbook.Sheets("OccupancyByDate")
Set excepWS = ThisWorkbook.Sheets("Telework Exceptions")
' Fill the 7 dates into header in OccupanyByDate sheet Columns E - K row 2
Dim i As Integer
i = 1
For j = 5 To 11 ' From column E(5) to K (11)
dates = WeekBeginningDate - Weekday(WeekBeginningDate, vbUseSystemDayOfWeek) + i
occWS.Cells(2, j).Value = Format(dates, "dd-mmm-yyyy") ' write dates to OccByDate sheet
'Save dates to datesArray
datesArray(i) = dates
stringDate = CStr(dates) ' convert date to string
If Mid(stringDate, 2, 1) <> "/" Then ' 2 digit month
tempMonth = Left(stringDate, 2)
Else
tempMonth = Left(stringDate, 1) ' 1 digit month
month = GetMonthAbbreviation(tempMonth)
End If
If Left(Right(stringDate, 7), 1) <> "/" Then '2 digit day
day = Left(Right(stringDate, 7), 2)
Else
day = Left(Right(stringDate, 6), 1) ' 1 digit day
' day = Mid(stringDate, 4, 2)
End If
year = Right(stringDate, 4)
stringDatesArray(i) = day & "-" & month & "-" & year
i = i + 1 ' Add 1 to increment date of week
Next j
''''''''''''''''''''''''
' Search for dates on the TW Exception Sheet
Dim numPerson As Long, Bldg As String, Room As String, foundDate As String
numPerson = 0
For i = LBound(datesArray) To UBound(datesArray)
'Search for datesArray(i) on TW Exceptions sheet
Set myRange = excepWS.Range("G:G")
Set LastCell = myRange.Cells(myRange.Cells.count)
Set FoundCell = myRange.Find(what:=stringDatesArray(i), after:=LastCell, LookIn:=xlValues)
If Not FoundCell Is Nothing Then ' if value found in column
FirstFound = FoundCell.Address
findRowNumber = FoundCell.Row 'get row number of the found date in the column on TW Excep sheet
foundDate = FoundCell.Text 'get text value of first occurence of new date found in column
Do ' Find additional occurences of date in the sheet column
findRowNumber = FoundCell.Row
If FoundCell.Offset(0, -3).Value = 1 Then
numPerson = 1
End If
If FoundCell.Offset(0, -2).Value = 1 Then
numPerson = 1
End If
Bldg = FoundCell.Offset(0, 3).Text
Room = FoundCell.Offset(0, 4).Text
FillDateCapacitiesInOccupancySheet foundDate, numPerson, Bldg, Room 'if i remove this line I don't get an error
Set FoundCell = myRange.FindNext(FoundCell)
If FoundCell Is Nothing Then
MsgBox "No Found Cell Address", vbInformation
Exit Sub
End If
Loop While (FoundCell.Address <> FirstFound)
End If
Next i 'Get next dateArray value
End If 'End if WeekBeginningString <> ""
End Sub
Sub FillDateCapacitiesInOccupancySheet(fndDate As String, numPpl As Long, Buildg As String, Rm As String)
Dim occWS As Worksheet
Dim FndCell As Range, rng As Range
Dim myNewRange As Range, LastCell As Range
Dim foundBldg As String
Dim findRowNumber As Long, count As Long
Dim dateOffset As Integer
Dim FirstFound As String
count = 0
Set occWS = ThisWorkbook.Sheets("OccupancyByDate")
Set myNewRange = occWS.Range("B:B") ' search in building column
Set LastCell = myNewRange.Cells(myNewRange.Cells.count)
Set FndCell = myNewRange.Find(what:=Buildg, after:=LastCell, LookIn:=xlValues)
If Not FndCell Is Nothing Then ' if value found in column
FirstFound = FndCell.Address
findRowNumber = FndCell.Row 'get row number of the found building in the column on OccByDate sheet
foundBldg = FndCell.Text 'get text value of first occurence of new building found in column
Do ' Find additional occurences of date in the sheet column
findRowNumber = FndCell.Row
If FndCell.Offset(0, 1).Text = Rm Then ' if room passed into function equals room for the building
'Find the date column for the date passed into function
For j = 5 To 11 ' From column E(5) to K (11)
If occWS.Cells(2, j).Text = fndDate Then
dateOffset = j - 2
count = FndCell.Offset(0, dateOffset).Value + numPpl
' write count to cell
FndCell.Offset(0, dateOffset).Value = count
End If
Next j
End If
Set FndCell = myNewRange.FindNext(FndCell)
Loop While (FndCell.Address <> FirstFound)
End If
End Sub
Any help would be greatly appreciated.
I get an Error 91 on the Loop While statement
Here:
Set FndCell = myNewRange.FindNext(FndCell)
Loop While (FndCell.Address <> FirstFound)
If that Range.FindNext call doesn't find anything, FndCell is Nothing when the While condition gets evaluated, and that would be where error 91 is being raised; the If Not FndCell Is Nothing Then parent block means nothing as soon as FndCell is re-assigned.
You need to bail out when FndCell is Nothing. Consider using Exit Do for this:
If FndCell Is Nothing Then Exit Do
Loop While FndCell.Address <> FirstFound
Only exiting the smaller scope conveys intent better than exiting the entire procedure scope here, I find - even if all that's left to execute [for now] is an End Sub statement.
Consider declaring j and having Option Explicit at the top of the module, too!

VBA script to format cells within a column range only formats the first sheet in the workbook

I have successfully scripted VBA code for summarizing and formatting a large set of data within a sheet. The script is successful when the macro is run on the next sheet I select. When tasked to apply the script across all sheets in the workbook, the modified script completes the summarizations for each sheet, but only formats the first. We tried to troubleshoot in my data class, but to no avail. This is an image of what it is supposed to look like.
My script for the whole workbook:
Sub tickerdata_all_ws()
'define variables
dim ws as Worksheet
Dim ticker As String
Dim stock_vol As Long
Dim yrclose As Double
Dim yrchange As Double
Dim yrvar As Double
Dim i As Long
Dim sumrow As Integer
Dim lastrow As Long
lastrow = ActiveSheet.UsedRange.Rows.Count
for each ws in Worksheet
'create the column headers
ws.Range("H1").Value = "Ticker"
ws.Range("J1").Value = "Yearly Change"
ws.Range("K1").Value = "Percent Change"
ws.Range("L1").Value = "Total Stock Volume"
'which row our summaries will be placed for above columns
sumrow = 2
'the loop checks each iteration until the last row
For i = 2 To lastrow
'we need to capture the price of the ticker if it is the first of its year
Dim firstprice As Boolean
If firstprice = False Then 'false is the default boolean value, so this statement is true
Dim yropen As Double
yropen = ws.Cells(i, 3).Value
firstprice = True 'we have captured the opening price of the year for the ticker
End If
'now we can check if we are in the same ticker value
If ws.Cells(i + 1, 1).Value <> ws.Cells(i, 1).Value Then
'this should happen when the cell values are finally different / capture all the values
ticker = ws.Cells(i, 1).Value
stock_vol = ws.Cells(i, 7).Value
yrclose = ws.Cells(i, 6).Value
yrchange = yrclose - yropen
If yropen <> 0 Then 'this prevents dividing by zero which will result in overflow error 6
yrvar = (yrclose - yropen) / yrclose
Else
yrvar = 0
yrchange = 0
End If
'insert values into the summary
ws.Cells(sumrow, 9).Value = ticker
ws.Cells(sumrow, 10).Value = yrchange
ws.Cells(sumrow, 11).Value = yrvar
ws.Cells(sumrow, 12).Value = stock_vol
sumrow = sumrow + 1 'sets the stage for the next set of data into row 3
stock_vol = 0 'resets vol for the next ticker
firstprice = False 'allows the next 'first' open price of the loop to be captured
End If
Next i 'finish i iteration of the loop
ws.Range("K:K").NumberFormat = "0.0%" 'aesthetic preference
'format columns colors
Dim colJ As Range
Dim Cell as Range
Set colJ = Range("J2", Range("J2").End(xlDown)) 'from J2 to the last cell entry
For Each Cell In colJ
If Cell.Value > 0 Then
Cell.Interior.ColorIndex = 50
Cell.Font.ColorIndex = 2
ElseIf Cell.Value < 0 Then
Cell.Interior.ColorIndex = 30
Cell.Font.ColorIndex = 2
Else
Cell.Interior.ColorIndex = xlNone 'this really serves no purpose
End If
Next
next ws
End Sub
I am sure there are other, much better ways to accomplish this, but as a novice, this is my code salad, and I'd appreciate any help as to why it is not formatting the other three sheets.
Excel for Mac user, though I've run it via Parallels as well.
Set colJ = Range("J2", Range("J2").End(xlDown)) 'from J2 to the last cell entry
here you get range for active sheet.
Change to:
Set colJ = ws.Range("J2", ws.Range("J2").End(xlDown))

how to extend the following excel VBA code [duplicate]

This question already has answers here:
Expand Start Date to End Date with Series of EOMONTHs
(2 answers)
Closed 5 years ago.
I want to generate month ending wise data for a given start and end period; number of months is varying for different applicants.
The following data is to be generated by user input and may vary in number per applicant:
Column ‘A’ -- month ending date
Column ‘B’ -- EMI
Column 'C' -- interest portion
Column ‘D’ -- principle portion
and so on.
I also want to calculate sum of each column at end and the row changing the size of sheet based on column “A” no of rows. Please help.
Sub GenerateDates()
Dim startDate As Date
Dim endDate As Date
Dim currentDate As Date
startDate = Range("b4").Value
endDate = Range("b8").Value
currentDate = startDate
Range("a17").Select
Do Until currentDate = endDate
ActiveCell.Value = currentDate
ActiveCell.Offset(1, 0).Select
'currentDate = DateAdd("m", 1, currentDate)
currentDate = DateSerial(Year(currentDate), Month(currentDate) + 2, 0)
Loop
End Sub
#Anil try this:
Sub GenerateDates()
Dim startDate As Date
Dim endDate As Date
Dim currentDate As Date
Dim cnt As Integer
startDate = Range("b2").Value
endDate = Range("b3").Value
currentDate = startDate
Range("a9").Select
cnt = ActiveSheet.Range("E3")
ActiveSheet.Range(ActiveSheet.Range("A10"), ActiveSheet.Cells(Rows.Count, Columns.Count)).ClearContents
With ActiveSheet.Range(ActiveSheet.Range("A9"), ActiveSheet.Range("A9").End(xlToRight))
.Copy
.Offset(1).Resize(cnt - 1).PasteSpecial xlPasteAll
End With
Application.CutCopyMode = False
For i = 1 To Range("A8").End(xlToRight).Column - Range("A8").Column
Range("A8").Offset(cnt + 1, i) = WorksheetFunction.Sum(Range("A8").Offset(1, i).Resize(cnt))
Next
End Sub
Click here to download the solution.
In the excel, there are 5 columns: End of month Date, EMI, Interest, Principal, Amount Outstanding. You have to 4 input fields: Start Period, End Period, Amount, Interest. The Calculate button runs the above macro. The first row, i.e. the 9th row has the formulas and are copy and pasted for the number of periods to get the dates and calculations. At the end, the summation of columns is taken. I hope this solves your problem!
Please try the following edit based on what I can understand on what you want to do:
Sub GenerateDates()
Dim startDate As Date
Dim endDate As Date
Dim currentDate As Date
Dim ws as Worksheet
Dim iRow As Long
Set ws = Worksheets("Sheet1") 'or whatever name of sheet you have
Set wbDesti = Workbooks.Open("C:\Users\...\DestinationFile.xlsx") ' <<< path to source workbook
Set sh = wbDesti.Worksheets("Sheet1") 'Sheet in destination file
'automatically find the last row in Sheet A.
iRow = ws.Cells.Find(What:="*", SearchOrder:=xlRows, _
SearchDirection:=xlPrevious, LookIn:=xlValues).row + 1
startDate = ws.cells(1,1).Value
endDate = ws.cells(2,1).Value
currentDate = startDate
'Range("a17").Select 'removed this to avoid .Select functions
dim row as integer 'declare another variable for row...
'row = iRow
'Do Until currentDate = endDate
'ws.cells(row,1).value = currentDate
'row = row + 1
'currentDate = DateAdd("m", 1, currentDate)
'currentDate = DateSerial(Year(currentDate), Month(currentDate) + 2, 0)
'Loop
Dim col as integer
col = 2 'start with B
Do until col = 4
sh.cells(1,col) = application.worksheetfunction.sum(ws.range("B"&10&":"&"B"&":"&60))
'***other codes goes here to transfer data same as above.
col = col + 1
Loop
wbDesti.quit
Set sh = Nothing
End Sub

sum of range amounts realated to the beginning of the month and today date

I wrote this code, but it gives an error. Can you please help me to correct it? I have two columns in excel: one shows the dates (each day, one after another), so that the last date in the column is "yesterday", and the second column shows relevant amounts. I need to write a formula by VBA calculating the sum of those amounts from the beginning of the month till the last row (last date, which is "yesterday"). As you may undertand the beginning of the month changes every month and the last date changes every day. - Thank you very much in advance!
Dim x As Long
x = Month(Workbooks("Reports.xlsm").Worksheets("MACRO").Cells(2, 3))
Range("F64").Formula = "=Sum(" & Range(Cells(Worksheets("A").Cells(Rows.Count, 4).End(xlUp).Row, 4), Cells(Worksheets("A").Cells(Rows.Count, 4).End(xlUp).Row - x, 4))
Yesterday is a Day(Now-1). So:
x = Day(Now-1)-1
Here's a way to find the 1st day of the month and yesterday's rows.
Sub FindYesterdayAnd1stDayofMonth()
' Turn Off screenupdating and calc to speed up code
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Dim wS As Worksheet
Set wS = ActiveSheet
Dim rFound As Range
Dim rS%, rE%
Dim M As Integer, Y As Integer
' Find 1st day of current month
M = Month(Now - 1)
Y = Year(Now - 1)
' Look in column A. Using a Range object to do some error checking when it doesn't work
Set rFound = wS.Columns(1).Find(What:=DateSerial(Y, M, 1), LookIn:=xlValues)
If rFound Is Nothing Then
MsgBox "Date '" & DateSerial(Y, M, 1) & "' not found"
Else
rS = rFound.Row
End If
' Find yesterday
Set rFound = wS.Columns(1).Find(What:=Date - 1, LookIn:=xlValues)
If rFound Is Nothing Then
MsgBox "Date '" & Date - 1 & "' not found"
Else
rE = rFound.Row
End If
' Turn updating and calc back on
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub

Resources