Find dates that fall within Monday-Sunday work week - excel

I currently have a program that finds dates within a table and compares them to a date range and uses them for something else. What I've been using for a week to compare against has been saying Date + 7, but I want to just take the dates of the current week from Monday-Sunday and use that as the Date range.
I think the way to go would be to use the current WeekNum and find the dates of the Monday and Sunday from there, but I honestly have no idea how to begin to do this from VBA. I would appreciate if anyone had a direction to send me in to accomplish this, or if I'm even thinking about this the right way.

Here is an easy way to get the Monday & following Sunday of the current week:
Sub getadate()
Dim N As Long
N = Weekday(Date)
d1 = Date - N + 2
d2 = d1 + 6
MsgBox d1 & vbCrLf & d2
End Sub

You can use the weekday formula to determine the start and end of the week. The formula would look as such:
startWeek = Date - (Weekday(Date, vbMonday) - 1)
and
endWeek = Date + (7 - Weekday(Date, vbMonday))
Let me know if this works

Related

Generate only weekend days in Excel

I am trying in Excel to show only weekend days, but the auto function is only able to show the weekdays.
I would like to obtain in the end a list of only Sat and Sun for a certain period.
Trying to use the WORKDAYS.INTL and WORKDAYS using the start date and a filtering on Sun/Sat, but in Excel 365 that is not working like expected.
Can somebody suggest something?
Thanks in advance.
With Office 365 Dynamic Array Formula:
=FILTER(SEQUENCE(B2-B1+1,,B1),WEEKDAY(SEQUENCE(B2-B1+1,,B1),2)>5)
If one does not have the Dynamic Array formula then one can put this in the first cell:
=IFERROR(AGGREGATE(15,7,ROW(INDEX($ZZ:$ZZ,$B$1):INDEX($ZZ:$ZZ,$B$2))/(WEEKDAY(ROW(INDEX($ZZ:$ZZ,$B$1):INDEX($ZZ:$ZZ,$B$2)),2)>5),ROW($ZZ1)),"")
And copy down.
Try the following User Defined Function:
Public Function weekends(d1 As Date, d2 As Date)
Dim c As Collection, i As Date, s As String
Set c = New Collection
For i = d1 To d2
s = Format(i, "dddd")
If s = "Saturday" Or s = "Sunday" Then
c.Add i, CStr(i)
End If
Next i
ReDim temp(1 To c.Count, 1 To 1)
For j = 1 To c.Count
temp(j, 1) = c.Item(j)
Next j
weekends = temp
End Function
In Excel 365 it should spill-down by itself.
EDIT#1:
If you have an older version of Excel (in my case Excel 2007/Win7) there is not automatic spill-down. Just select a block of cells in the column and array-enter the formula.

Excel VBA count non business days/weekend days

**Hello all,
I have a question that is ½ about the code and ½ about the logic behind the code.
Background:
This is a vary small part of one Sub in a large workbook collection. The goal of this bit of code is to accept a user input for the number of business days they want to look out for a date range. Determine if the dates between contain weekend days, if so, add 2 to the range. The input is data type Integer. The number is added to the current date to get the last date in the range and assigned to dDate for use in this and other Sub’s.
What the code should do:
The most a user can request to look out for is 14 (don’t need error handling for more then 14). The request can be made any day of the week including weekends. If a request is made on Wednesday to look out 3 business days, the program should add 2 to show Thursday, Friday, Saturday, Sunday, and Monday. If the request is made on a Saturday to show 2 business days the program should add 1 to show Sunday, Monday, and Tuesday. If the number requested has 2 weekends between the range (8-14) then add 4.
So in short, for every weekend day in the date range, add one day to the user input number.
Please explain any responses with in code comments for all VBA skill levels.
Both Code and logic help is welcome.
**
'prompt to enter number of days to look out for shortage, new addition to the code added to expand usability
iNumDays = Application.InputBox(prompt:="Enter number of business days to look out for")
iweekday = Weekday(Date, vbMonday) 'get todays weekday number 1-7 with Monday being 1, Sunday being 7
'if today is Thursday or Friday the next 2 business days fall on the weekend, if so then we need to look out 2 days more
If iweekday > 3 Then 'iweekday is integer of todays weekday number, if its past Wednesday then enter If
iNumDays = iNumDays + 2 'add 2 to user input
End If
dDate = Date + iNumDays 'add user day to look out input to todays date to get last date in desired date range 'get the column header for the date we are looking out to
Solution found here: https://www.experts-exchange.com/questions/23461938/VB-net-Add-Days-to-a-Date.html
Public Function AddNBusinessDays(ByVal startDate As DateTime, ByVal numDays As Integer) As DateTime
If numDays = 0 Then Return New DateTime(startDate.Ticks)
If numDays < 0 Then Throw New ArgumentException()
Dim i As Integer
Dim totalDays As Integer
Dim businessDays As Integer
totalDays = 0
businessDays = 0
Dim currDate As DateTime
While businessDays < numDays
totalDays += 1
currDate = startDate.AddDays(totalDays)
If Not (currDate.DayOfWeek = DayOfWeek.Saturday Or currDate.DayOfWeek = DayOfWeek.Sunday) Then
businessDays += 1
End If
End While
Return currDate
End Function
The most intuitive way to do this (in my opinion) is to simply count the days forward one by one until you added as many work days as requested by the user. The 14 days limit is not necessary anyways, as it is a loop that works with any integer up to billions of days...
Sub adddays()
Dim iNumDays As Integer
Dim iWeekDay As Integer
Dim dDate As Date
'prompt to enter number of days to look out for shortage, new addition to the code added to expand usability
iNumDays = Application.InputBox(prompt:="Enter number of business days to look out for")
dDate = Date ' initialize dDate with today's date before entering the counting loop
While iNumDays > 0 ' as long as the there are still workdays left to add, repeat this
dDate = dDate + 1 ' move calendar forward by one day
iWeekDay = Weekday(dDate, vbMonday) ' check what weekday we arrived at
If iWeekDay < 6 Then ' if we're looking at a working day, we successfully added one of the desired weekdays to be added
iNumDays = iNumDays - 1
End If
Wend
MsgBox ("Target date is: " & Str(dDate)) 'check results of the calculation or replace with whatever other logic you want here
End Sub

Finding oldest date in column with separated data

I am making a function that will search through a range and find the oldest date (the oldest date is in last row with data). My range is structured as following and I won't be able to change this structure:
Year Month Day
yyyy mm dd
So the year month and day are seperated in three different columns.
My code is as following:
Function OLDEST(yearrng As Range) As Variant
Dim lastrow As Long
Dim year, month, day As String
lastrow = Range(yearrng).SpecialCells(xlCellTypeBlanks).Row
year = Range("I" & lastrow).value
month = year.Offset(0, 1).value
day = year.Offset(0, 2).value
OLDEST = year & month & day
End Function
The yearrng is the same range which the years are displayed.
The problem is that this function is not working and is returning "value error"...
I hope you understood my question.
Thanks!
For a non-volatile worksheet function, you can try:
=DATE(LOOKUP(2,1/(LEN($I:$I)>0),I:I),LOOKUP(2,1/(LEN($I:$I)>0),J:J),LOOKUP(2,1/(LEN($I:$I)>0),K:K))
where I is the column to test for which is the "bottom" row, and I, J, and K are the columns with the relevant date parts.

Excel Formula - Comparing Range of Date

how to write EXCEL VBA to make my date from 04/JUNE > 04/JUNE 23:59. i cannot use the '= date + 5/6' as i have to run the VBA many times a day and it will add my dates to tomorrow/ the day after tomorrow. i just wanna make the date to end of date. please help.
The example will be like
CELL A1 : 12/June
CELL B1 : 15/June
CELL C1 : 15/June 12:00 HRS
CELL D1 : =IF C1B2, “OUT OF RANGE”, “Okay !”)
in this case D1 will still display OUT OF RANGE.
I have loads of such to change so I was thinking of writing a VBA to automatically convert C1 from 15/JUNE -> 15/JUNE 23:59 , so that D1 will display Okay !
I tried Cdate(Range(“D1”)) + 5/6 in vba to make it 23:00 hrs and I run this macro a few times in a day and it will keep adding 23hrs to the date and made it change to another date.
About what you are talking?
About:
- "Excel Formula" or
- "EXCEL VBA"
?
About:
- "Comparing Range of Date" or
- "to make my date"
?
Assume, that VBA is...
The Date type in VBA is Double, where:
- Integer part as quantity of days from... (look F1), and
- Fractional part of day.
So, your desired "04/JUNE > 04/JUNE 23:59" will:
? DateSerial(2018, 06, 4) + ((23& * 60& * 60&) + (59& * 60&)) / 86400&
18-06-04 23:59:00
Yeah, sure, you can use TimeSerialinstead of above, but ... it didn't give you right understanding of VBA dates.
.
----------
ADD:
Sorry but will this code only work for one cell because I have lots of
cells with dates and I need VBA to extract them out and convert to
23:59 for eg I run a for loop to change like 20 cells in a row with
multiple range. And I will run the macro a few times in a day will it
add 23hrs to that date every time and cause it to change dates ?
Public Sub sp_Test_Date()
Dim rSel As Range
Dim i&
Const H23M59 As Double = 1 - 60 / 86400
Set rSel = Selection
With rSel
For i = 1 To .Cells.Count
With .Cells(i)
If IsDate(.Value) Then
.Offset(0, 1).Value = CDate(Int(.Value) + H23M59)
End If
End With ' .Cells(i)
Next
End With ' rSel
End Sub
i tried modifying it to below and it failed me :(
`
Dim x As Integer
Dim test1 As Date
Dim schdWS, compWS As Worksheet
Const H23M59 As Double = 1 - 60 / 86400
Set schdWS = Sheet1
Set compWS = Sheet11
lastrow = schdWS.Cells(Rows.Count, 8).End(xlUp).Row
For x = 20 To lastrow
If IsDate(schdWS.Cells(x, 3).Value) Then
Cells(x, 3).Value = CDate(Int(Cells(x, 3).Value + H23M59))
End If
'test1.NumberFormat = "dd/mm/yyyy"
'schdWS.Cells(x, 3).FormulaR1C1 = test1 & " 23:59"
Next x
End Sub
`

Working with dates in Visual Basic / Excel

Very new to working with Visual Basic / Excel. I am trying to write a quick script that enters the current time in one column, and allows the user to enter how many days/hours/minutes will pass until a new time, and output that in another column.
I'm sure this isn't the best way to do it, but what I have so far is the following. I have given up on fiddling with dates, and am just working with the time:
Sub TimeModule()
Dim DaysLeft, HoursLeft, MinutesLeft As Double
DaysLeft = Val(InputBox("Days left"))
HoursLeft = Val(InputBox("Hours left"))
MinutesLeft = Val(InputBox("Minutes left"))
Dim CurrentTime As Date
CurrentTime = TimeValue(Now())
ActiveCell.Value = CurrentTime
ActiveCell.Offset(0, 1) = CurrentTime + Time(HoursLeft, MinutesLeft, 0)
End Sub
I am getting an error, of course. If anyone could shed some light on a better way to do this, along with the functions I'm misusing, I would really appreciate it!
Edit: I would, of course ultimately like for the script to handle days as well.
I think this is possible just using cell functions in Excel, if I've understood you correctly.
For example, this is what you'd see...
Time Now: Days: Hours: Minutes: New Time:
30/05/2012 23:34 15 6 23 15/06/2012 05:57
...and this is what is in each cell (assuming top-left cell is A1)...
Time Now: Days: Hours: Minutes: New Time:
=NOW() 15 6 23 =A2+B2+TIME(C2,D2,0)
Describing each function:
NOW() returns the current date and time formatted as a date and time.
DATE(year,month,day) returns the number that represents the date in MS Excel date-time code.
TIME(hours,minutes,seconds) converts hours, minutes, and seconds given as numbers to an Excel serial number, formatted with a time format.
Dissecting the equation in the last cell:
A2 is the cell containing the current date/time (as of last worksheet calculation).
B2 is the user-inputted value for days.
TIME(C2,D2,0) is the TIME() function, taking the user-inputted values for hours and minutes from cells C2 and D2 respectively.
Is this anything like your intended functionality...?
If you want to use VBA the only issue with your code is the "Time" function.
You can use CDate instead :
Sub TimeModule()
Dim DaysLeft, HoursLeft, MinutesLeft As Double
DaysLeft = Val(InputBox("Days left"))
HoursLeft = Val(InputBox("Hours left"))
MinutesLeft = Val(InputBox("Minutes left"))
Dim CurrentTime As Date
CurrentTime = TimeValue(Now())
ActiveCell.Value = Now()
ActiveCell.Offset(0, 1) = ActiveCell.Value + DaysLeft + CDate(HoursLeft & ":" & MinutesLeft)
'ActiveCell.Offset(0, 1) = CurrentTime + Time(HoursLeft, MinutesLeft, 0)
End Sub
When you 'Dim' in that fashion, you have to record the data type for each variable. The way you have it MinutesLeft is a Double and everything is (by default) a Variant.
The Time function you're looking for is TimeSerial.
Dates are stored as the number of days since a certain date. To add days to a date, you can simply add the numbers together.
Sub TimeModule()
Dim lDaysLeft As Long
Dim lHoursLeft As Long
Dim lMinutesLeft As Double
Dim dtCurrent As Date
lDaysLeft = Val(InputBox("Days left"))
lHoursLeft = Val(InputBox("Hours left"))
lMinutesLeft = Val(InputBox("Minutes left"))
dtCurrent = Now()
ActiveCell.Value = dtCurrent
ActiveCell.Offset(0, 1).Value = dtCurrent + lDaysLeft + TimeSerial(lHoursLeft, lMinutesLeft, 0)
End Sub

Resources