Move Excel Data Based On Date Column - excel

I am trying to move data from a 5 column spread sheet in excel to other sub spread sheets based on one of the date columns in the first spread sheet. The sub-spreadsheets will be created if they do not exist, otherwise they will be populated with data from the master spreadsheet. The spread sheets names will be a date that is the start of the week(being monday). my columns are: Work Order, Description, Location, Asset, Date.
Example:
Work Order - Description - Location - Asset - Date
123 ---------- test&inspect - NC-231 - KK32 - 8/21/14
In this example my master spreadsheet with a date row of 8/21/14 will create a subspread sheet with a name of 8/18/14 since this row falls in the week of 8/18/14 and insert the other columns with it. How can this be done inside of an excel workbook?

Dim firstDate As Date, secondDate As Date
Dim I as Date
firstDate = Inputbox("What start date?") ' request your input for what date Monday is
secondDate = DateAdd("d", 6, firstDate)
For Each Cell in Range("E2"),Range("E2").End(xldown)
ActiveCell = Cell
If cell => firstdate and =< secondate then ' test if falls under days of week
ActiveCell.Row.Copy
On error resume next
Worksheets.Add.Name = Firstdate
Sheets(" & Firstdate &").Select
Range("A1").End(lxDown).Offset(1,0).pastespecial
Next Cell
End Sub
Not tested but should be a start .

Related

Take a summary of cell values from the last 5 days of workbooks into single workbook

I have a requirement that once a week on a Friday I need to pull some data from workbooks generated each day of the week (Mon-Fri) into a weekly dated summary in a new workbook. The new workbook is to be a cumulative view of each week with the date auto populated on the Friday when the data is pasted into the summary sheet.
I need some pointers on how to logically work out the current date, search back to find the first file from that Monday (but include Friday's file) and then to insert the range of dates from that week into the corresponding cells next to the copied data.
I've found various posts from others looking to do a similar thing, and I've attempted to begin working on that basis to produce what I want it to do. However, I'm not trained in VBA so I am attempting everything on a 'best efforts' basis. The below is the code I have written which currently just opens up the last file in the directory. I also have a separate tab with the public holidays I want it to take into account when running the macro. Clearly there's a lot for me to do, I would be grateful for any tips and pointers on what I should try.
Sub WeeklyUpdate()
Dim wsCopy As Worksheet
Dim wsDest As Worksheet
Dim lCopyLastRow As Long
Dim lDestLastRow As Long
Dim LastPreviousWorkday As Date
'date format to use and where to lookup the bank holidays
LastPreviousWorkday = Application.WorksheetFunction.WorkDay(Date, -1)
LastPreviousWorkday = Format$(LastPreviousWorkday, ("yyyy-mm-dd"))
LastPreviousWorkday = Application.WorksheetFunction.WorkDay(Date, -1, Worksheets("PublicHolidays").Range("A:A"))
'This is where I want it to opens the last 5 days of workbooks from today's date including today e.g. Monday-Friday, report is always run on a Friday
Workbooks.Open "W:\Inventory\Inventory Support\3. Reporting\Daily\Daily Fails Report\Daily Fails Report " & Format(Date, "yyyy-mm-dd") & ".xlsb"
'Set variables for copy and destination sheets
Set wsCopy = Workbooks("Daily Fails Report 2019-06-26.xlsb").Worksheets("Daily Fails Report (National)")
Set wsDest = Workbooks("Weekly Issues Summary.xlsb").Worksheets("CurrentPeriodSummary")
'Find last used row in the copy range based on data in column O
lCopyLastRow = wsCopy.Cells(wsCopy.Rows.Count, "O").End(xlUp).Row
'Find first blank row in the destination range based on data in column B
'Offset property moves down 1 row to exclude headers
lDestLastRow = wsDest.Cells(wsDest.Rows.Count, "B").End(xlUp).Offset(1).Row
'Copy data range excluding the grand total which is always the last row (so use -1 to select the last row above it) & Paste Data into Summary
wsCopy.Range("O9:Q" & lCopyLastRow - 1).Copy _
wsDest.Range("B" & lDestLastRow)
End Sub
I expect the output of the above to update my summary workbook with five lines of data per week with a date against each one that corresponds to the date in the name of the file.
I need some pointers on how to logically work out the current date, search back to find the first file from that Monday (but include Friday's file) and then to insert the range of dates from that week into the corresponding cells next to the copied data.
The following function outputs the date range (as an array), from Today going back to the previous Monday.
Option Explicit
Function dateStuff() As Date()
Dim lastMonday As Date
Dim arrDates() As Date
Dim I As Long
lastMonday = Date - Weekday(Date, vbMonday) + 1
ReDim arrDates(0 To Date - lastMonday)
For I = 0 To UBound(arrDates)
arrDates(I) = lastMonday + I
Next I
dateStuff = arrDates
End Function
You can then use the output of this function to create the names for the corresponding workbooks.
If I understand what you are doing correctly, there shouldn't be a need to exclude holidays from this list. Since you won't have a workbook generated for a holiday, just test to see if the workbook exists when you are trying to obtain the data.
Here's a routine to put the generated date range into some cell. You can work out how to change rOutput to reflect your real target cell. This Sub depends on the above Function:
Sub insertDateRange()
Dim dateRange() As Date
Dim rOutput As Range
Set rOutput = Worksheets("sheet1").Range("B1")
dateRange = dateStuff
rOutput = dateRange(0) & " - " & dateRange(UBound(dateRange))
End Sub
Run Today 27-Jun-2019 the macro will output 6/24/2019 - 6/27/2019
but you can use the VBA Format function to change the output format of the dates if you desire.
EDIT:
So far as opening the workbooks and processing them, it's just a matter of iterating through the output of the dateStuff function to generate your workbook paths. eg:
'This is where I want it to opens the last 5 days of workbooks from today's date including today e.g. Monday-Friday, report is always run on a Friday
Dim wbDates() As Date, Idx As Long
Dim wbDaily As Workbook, wbPath As String
wbDates = dateStuff 'wbDates now contains an array of the relevant dates
'This will open the workbooks one at a time and you can process them as you wish
'You should refer to this daily workbook as `wbDaily` or some other variable of your choice
For Idx = LBound(wbDates) To UBound(wbDates)
wbPath = "W:\Inventory\Inventory Support\3. Reporting\Daily\Daily Fails Report\Daily Fails Report " & Format(wbDates(Idx), "yyyy-mm-dd") & ".xlsb"
If Len(Dir(wbPath)) > 0 Then 'workbook exists
Set wbDaily = Workbooks.Open(wbPath)
'your code
'.....
wbDaily.Close
End If
Next Idx

How to display only year in vba?

I have the following data set in general formatting.
Bunch of years with no day nor months provided.
What I want to achieve, is to display the date in yyyy format.
I made a standard DateSerial function to convert the data to date properly.
Private Function toDate(ByVal text As String) As Date
toDate = DateSerial(Int(text), 1, 1)
End Function
For Each cell in ws.Range("A21:A" & lr)
cell = toDate(cell)
cell.NumberFormat = "yyyy"
Next cell
Now, technically this works, but if you click inside the cell, it
obviously shows the date only as 01-01-year - that is to be expected
with usage of dateserial
But I was wondering, would it be possible given my data to somehow
omit the Days and Months and only display the result as a year?
Basically, I need want to convert the data to a Date data-type without specifying days and months
Entering the years and formatting the date as "YYYY" could be done like this:
Sub TestMe()
With ThisWorkbook.Worksheets(1)
.Range("A1") = 2011
.Range("A2") = 2013
.Range("A3") = 2011
Dim myCell As Range
For Each myCell In .Range("A1:A3")
myCell = DateSerial(myCell, 1, 1)
myCell.NumberFormat = "yyyy"
Next myCell
End With
End Sub
The "trick", is that DateSerial(myCell, 1, 1) takes the year from the cell and adds 1 for day and January for month. Thus, every year is represented as the date 1.January from that year.
More about the Date in VBA and Excel - VBA doesn't return the correct Date with Now()

Selecting a range of cells

I am attempting to change sheet names while increasing selected dates by one (1) year.
OCT is the beginning of a new fiscal year (FY) and I'm trying to adjust accordingly. For example OCT-17, NOV-17, DEC-17, JAN-18, etc. I'm trying to change to OCT-18, NOV-18, DEC-18, JAN-19 in order to clear previous data and enter the new FY information.
Thus far, I have been able to adjust sheet names, however I am stumbling on being able to "select" the range of dates that I am attempting to adjust for the new FY. I am attempting to select the range of dates and add one (1) year to each of the dates in order to reference accurate data as the table references a pivot table as its data source.
Dim MyDate As String
Dim Cell as Range
MyDate=Format(DateSerial(Year(Date), Month(10), 1, "yy")
If FormMonth = "OCT" then
sheet1.name = "FY" & MYDate - 3
sheet1.range("B9:M9").select
For Each Cell in selection
cell.value = DateAdd("yyyy", 1, CDate(cell.value))
Next cell
End If
I have MyDate - 3 to change the sheet names as I have separate sheets that hold the previous 3 years of FY data. That successfully changes the year to the FY information I would like to present.
My script is not liking the sheet1.range("B9:M9").select.
You need to set sheet1 to a worksheet:
mySheetName = "FY" & MYDate - 3
Set sheet1 = Worksheets(mySheetName)
That said, you really want to avoid using Activate/Select in your code. Something like:
For Each Cell in sheet1.range("B9:M9")
cell.value = DateAdd("yyyy", 1, CDate(cell.value))
Next cell

Excel macro to find weekend from day number

I have an Excel macro which calculates no. of hours spent on a task for each day in a month.
The first row contains day numbers from 1 to 31 and data is filled using the macro accordingly for each day number for a month. The sheet name contains the month name.
Now, the problem is the macro leaves blank for the days for which data is not available. That day can be a Saturday, Sunday, or the person was absent that day.
I want the macro to identify weekends and highlight those with gray color so that only absent days appear as blank.
Using cell formulas and conditional formatting (VBA below)
You could do this quite easily with the built-in WEEKDAY cell formula, together with the DATE formula.
By setting up the year and month value in the sheet, you can create an extra column which gives the day of the week as a number between 1 and 7:
=WEEKDAY(DATE($A$2, $B$2,C2))
Then you can set up conditional formatting to colour days 7 and 1 (Saturday and Sunday respectively) grey
Using VBA
You can apply the same logic as above, but from a sub. This doesn't require the month and year values to be stored in the sheet, and takes the month from the sheet name. It then directly colours the day number grey if on the weekend.
Sub weekdayhighlight()
Dim days As Range
Set days = ActiveSheet.Range("C2:C8") ' Range where date numbers are stored, 1,2,...,31
Dim month As String
month = ActiveSheet.Name ' Active sheet name is "May"
Dim day As Range
Dim daynum As Long
' Loop over days to test for weekday
For Each day In days
' Get day number, from date in format "1 May, 2017"
daynum = Weekday(DateValue(day.Value & " " & month & ", 2017"), firstdayofweek:=vbSunday)
If daynum = 7 Or daynum = 1 Then
day.Interior.Color = RGB(200, 200, 200) ' Grey for saturdays or sundays
End If
Next day
End Sub
Note: This macro will throw an error if you try and compute the weekday of a non-existant date, for instance the 31st of Feb. You say each sheet has day numbers from 1 to 31, you should limit that to actual existing dates or add error handling to the code.
Try combining your sheet name and column headers into date (what about a year?) in a loop and then use DatePart() function to determine whether it is weekend day or not. It would be easier if column headers were real dates (may be formatted to show day only).

Converting all dates in a year into multiple strings using Excel VBA

I have to write a vba code that convert all dates in a year into days in a week eg. Monday, Tuesday, Wednesday....Sunday and the value of all days in a week eg.Monday must be in a string format. (See image inserted)
I tried using the .NumberFormat function but it does not work since the format is still under the date format although the values displayed are correct (please look at the formula bar of F10). Below is the code I have written:
Sub convertdate()
Range("A7:A371").Copy
'copy all the dates throughout the year'
Range("F7:F371").PasteSpecial xlPasteFormulasAndNumberFormats
'paste it into F column'
Worksheets("Sheet1").Range("F7:F371").NumberFormat = "dddd"
'convert the dates into days'
Sum1 = Application.SumIf(Range("F7:F371"), "Monday", Range("B7:B371"))
'example of calculating the total rainfall of all Mondays throughout the year'
Worksheets("Sheet1").Range("G22").FormulaArray = Sum1
End Sub
The formula bar from cell F7:F371 should display the string value "Monday","Tuesday" etc depending on the dates rather than the date itself.The reason of converting it into a string is so that it could be use in a SUMIF function later on to calculate the total rainfall of all Mondays,Tuesday etc.
Appreciate if anyone could help. Thank you.
A formula can do this.
In cell F7 enter =TEXT(A7,"dddd") and drag down.
This will format the date to show the full day name as a string.
https://support.office.com/en-us/article/TEXT-function-20d5ac4d-7b94-49fd-bb38-93d29371225c
Try something like this. It will loop through all the dates in Column A (starting in row 7) and put the associated Weekday name in Column F:
Sub test()
Dim i As Long
Dim lRow As Long
With ActiveSheet
lRow = .Cells(.Rows.Count, 1).End(xlUp).Row
For i = 7 To lRow
.Cells(i, 6).Value = WeekdayName(Weekday(.Cells(i, 1).Value, 1), False, 1)
Next i
End With
End Sub

Resources