I am trying to simplify a process for field employees at my work. The baseline case is that the employees fill out Daily Detail Reports in a single Excel Workbook throughout the year with the hours they have worked that day, the project # and Phase Code their labor costs will hit and the hours that they worked that day on that particular project. It is very common for the same project number and phase code to be used more than once for a single day (i.e. multiple row entries which will need the total hours added together based on the condition of having the same project number and phase code for that day). See attached "Detail Report WB" image.
Our employees then have to enter the same data in a different format (i.e. only one line allowed per project number and phase code pair per day) in a separate workbook. See attached "Timesheet Import WB" image. The timesheet workbook is driven based on the week end date for that week (i.e. Sunday). The Daily Detail Report workbook however, is driven based on the week beginning date and Sundays are not included in the Daily Detail Report. To make things more complicated, the dates listed in the Daily Detail report are based on formulas and do not house the actual date value in the cells.
The goal of this solution is to take the information entered into the Daily Detail Report workbook and place it into the Timesheet workbook via a sub function based on a ActiveX command button click event. See the attached “End Goal” image.
So far I have compiled the following code to allow the user to click the import button which prompts the user to find the Daily Detail Report workbook that they would like to import data from. This code also allows for the user to input the week end date desired for the Timesheet workbook. I was trying to use the week end date to find the desired data in the Daily Detail Report workbook, but this is proving difficult. Any assistance would be greatly appreciated. It’s been years since I took into to computer programming in VBA back in college.
Images are located here: https://drive.google.com/drive/folders/0B7BjXxM59FFyQlM5eThvc0dDWUU?usp=sharing
Thanks!
Private Sub CommandButton1_Click()
'Define All Variables
Dim GCell As Range
Dim fDialog As FileDialog, result As Integer
Dim MyDetailReport As String
Dim MyTimeSheet As String
Dim MySheet As String
Dim ProjNum As String
Dim PhaseCode As String
Dim Hours As String
Dim WkEndDate As String
'Find source file
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
fDialog.AllowMultiSelect = False
fDialog.Title = "Select Daily Report File to Import"
fDialog.InitialFileName = "W:\PDX - Mechanical Construction\Operations\Detailing\Daily Tracking Logs\"
fDialog.Filters.Clear
fDialog.Filters.Add "Excel files", "*.xlsx"
If fDialog.Show = -1 Then
MyDetailReport = fDialog.SelectedItems(1)
End If
'Enter date to look for in workbook
WkEndDate = InputBox("Insert Week End Date in format mm/dd/yyyy", "User date", Format(Now(), "mm/dd/yyyy"))
If IsDate(WkEndDate) Then
WkEndDate = Format(CDate(WkEndDate), "mm/dd/yyyy")
'Place Week End Date into Timesheet workbook
With ThisWorkbook.ActiveSheet.Range("AE5")
.Value = WkEndDate
End With
Else
MsgBox "Wrong date format"
End If
'Use the current sheet to store found data
MySheet = ActiveSheet.Name
'Use Error Handling routine in case of errors
On Error GoTo ErrorHandler
'Turn off screen updating to run macro faster
Application.ScreenUpdating = False
Workbooks.Open Filename:=MyDetailReport & MyTimeSheet
'Search Detail Report "Daily Report Log" sheet for the selected Week End Date
Set GCell = ActiveSheet.Cells.Find(WkEndDate, LookIn:=xlValues)
GCell = GCell.Offset(2, 1)
If GCell.Value = "" Then
GCell = GCell.Offset(1, 0)
Else
'copy data formulas to correct format for Timesheet workbook
End If
'Error Handling
ErrorHandler:
Select Case Err.Number
'Common error #2: the specified data wasn't in the target workbook.
Case 9, 91
Application.ScreenUpdating = True
MsgBox "The value " & WkEndDate & " was not found."
Exit Sub
'General case: turn screenupdating back on, and exit.
Case Else
Application.ScreenUpdating = True
Exit Sub
End Select
End Sub
I am trying to reference a file that has the date of the previous Friday at the end in the form of mm.dd.yy.
I need to now take that date and add it to the end of a string, to end of a string in order to open select the other workbook. This is what I have right now.
File Name:
Submittals Wk Ending 06.02.17.xlsx
This is what I have so far
Dim wrbk As String
Dim weekdate As String
range("a1").value="=TODAY()-WEEKDAY(TODAY())-1"
weekdate = Range("a1").Value
'range("b1").value="06.02.17"
'weekdate = Range("b1").Value
msgbox weekdate 'use to check what the date format is
wrbk = "Submittals Wk Ending " & weekdate
Windows(wrbk & ".xlsx").Activate
When I read it from B2 with the typed in format of 06.02.17 it works, however no matter what I do, I cannot get it to read it from A1 because it changes the format to m/d/yyyy. I have tried to copy it and paste as value. Nothing seems to work.
I have the other workbook open as well when I try to run it.
Any ideas? Thanks!
To get the previous Friday of any date, try below UDF. This should work fine if the Date NumberFormat is same as your System's Date format. The key is the CDate() which converts according to System's Date format which Office apps defaults to.
Option Explicit
Function GetLastFridayDate(AnyDate As Variant) As Date
Dim dInput As Date, dLastFriday As Date
dInput = CDate(AnyDate)
dLastFriday = dInput - Weekday(dInput) + vbFriday - IIf(Weekday(dInput) > vbFriday, 0, 7)
GetLastFridayDate = dLastFriday
End Function
Try
Range("A1").Value = Format$(Date - Weekday(Date) - 1, "MM.DD.YY")
I have the below code to open up files with variable file names, due to dates being in them. I personally save each file daily with the date stamp, ie this morning I saved a file with yesterday's date, 4.20.17.
This code will be run every Friday morning, and the goal is to load the last 5 work days' files (last Friday, this Monday, Tues, Wed, Thurs) grab some info out of those files (copy 2 cells from each), paste that info in a new sheet, and finally close each file.
Currently, the code is set to tell me when a file does not exist (for instance, last Friday was Good Friday, so Monday morning, I did not create any file for last Friday), and then ignore and move past that day.
The issue I currently have (besides the code being long and can probably be concatenated) is that a file exists for last Thursday, yet my code tells me there is none. I have been advised that this is because the code is actually looking at today (Thursday) and not a week ago Thursday, where there actually is a file.
Any assistance is appreciated. I removed a few days to make the below code less of a bear to look at, and a sample filename is "Agent Group Daily Summary 4.19.17"
Const strFilePath As String = "D:\Users\stefan.bagnato\Desktop\Daily Performance Summary\Agent Group Daily Summary "
Dim LastFridayDate, MondayDate, TuesdayDate, WednesdayDate, ThursdayDate As String
Dim fullFileNameLastFriday, fullFileNameMonday, fullFileNameTuesday, fullFileNameWednesday, fullFileNameThursday As String
Dim wbkLastFriday, wbkMonday, wbkTuesday, wbkWednesday, wbkThursdayOpen As Workbook
LastFridayDate = Format(Date - (Weekday(Date, vbFriday) - 1), "m.d.yy")
fullFileNameLastFriday = strFilePath & LastFridayDate & ".xls"
If Dir(fullFileNameLastFriday) = "" Then
MsgBox "File for last Friday doesn't exist!"
GoTo ExitLastFriday
End If
Set wbkLastFriday = Workbooks.Open(fullFileNameLastFriday, False, True)
Call BasicDailySummary
wbkLastFriday.Activate
Range("T2:T8").Copy
fp.Activate
Range("B3:B9").PasteSpecial xlPasteValues
wbkLastFriday.Activate
Range("F2:F8").Copy
fp.Activate
Range("G3:G9").PasteSpecial xlPasteValues
wbkLastFriday.Close SaveChanges:=False
ExitLastFriday:
MondayDate = Format(Date - (Weekday(Date, vbMonday) - 1), "m.d.yy")
fullFileNameMonday = strFilePath & MondayDate & ".xls"
If Dir(fullFileNameMonday) = "" Then
MsgBox "File for Monday doesn't exist!"
GoTo ExitMonday
End If
Set wbkMonday = Workbooks.Open(fullFileNameMonday, False, True)
Call BasicDailySummary
wbkMonday.Activate
Range("T2:T8").Copy
fp.Activate
Range("C3:C9").PasteSpecial xlPasteValues
wbkMonday.Activate
Range("F2:F8").Copy
fp.Activate
Range("H3:H9").PasteSpecial xlPasteValues
wbkMonday.Close SaveChanges:=False
ExitMonday:
....................................
ThursdayDate = Format(Date - (Weekday(Date, vbThursday) - 1), "m.d.yy")
fullFileNameThursday = strFilePath & ThursdayDate & ".xls"
If Dir(fullFileNameThursday) = "" Then
MsgBox "File for Thursday doesn't exist!"
GoTo ExitThursday
End If
Set wbkThursday = Workbooks.Open(fullFileNameThursday, False, True)
Call BasicDailySummary
wbkThursday.Activate
Range("T2:T8").Copy
fp.Activate
Range("F3:F9").PasteSpecial xlPasteValues
wbkThursday.Activate
Range("F2:F8").Copy
fp.Activate
Range("K3:K9").PasteSpecial xlPasteValues
wbkThursday.Close SaveChanges:=False
ExitThursday:
That a file exists for last Thursday, yet my code tells me there is none
As I explained in the other question you asked yesterday, putting the vbMonday or vbThursday etc in the Format function doesn't magically tell VBA to return that day:
Hint: The vbFriday part of the Weekday function is not magically telling it to get friday's date. It's actually telling it that, for the sake of this function call, consider Friday to be the first day of the week. The Weekday function then returns an integer (the ordinal day of the week) which it subtracts from the Date.
So, you need to go back and understand how those functions work, you can't just dump constants in there willy-nilly without making an effort to understand what they're doing, or why. On that note, you absolutely need to read this and learn how to begin debugging and troubleshooting first. This describes basics of how to step through your code and examine variable's values/etc at runtime. These techniques are foundations you need to work with VBA.
Here is a list of statements available in VBA. This is documentation that explains things like "How to create a loop structure with For/Next, etc."
And you should go back through the dozen or so questions you've asked here, and mark accepted answers for those where an answer has solved your problem. This is just a basic point of etiquette: You've asked 11 questions here and only accepted 1 answer.
Note also that this sort of declaration does not do what you think it does:
Dim LastFridayDate, MondayDate, TuesdayDate, WednesdayDate, ThursdayDate As String
Dim fullFileNameLastFriday, fullFileNameMonday, fullFileNameTuesday, fullFileNameWednesday, fullFileNameThursday As String
Dim wbkLastFriday, wbkMonday, wbkTuesday, wbkWednesday, wbkThursdayOpen As Workbook
Only the last item in each of those statements are strongly typed, the rest are implicitly variant. You should strongly type all variables when possible, e.g.:
Dim wbkLastFriday As Workbook, wbkMonday As Workbook, wbkTuesday As Workbook, wbkWednesday As Workbook, wbkThursdayOpen As Workbook
And rather than using five different workbook objects (unless you really need 5 workbooks open at once, just use a single workbook object and operate within a loop, opening successive file at each iteration.
Dim wb as Workbook
Dim i as Long
For i = 1 to 5
Set wb = Workbooks.Open(...)
'Do something
wb.Close()
Next
Getting to your actual problem:
A function like below will return an array of your date components. This returns the previous 7 days from the FirstDay (which defaults to Friday previous). You can use the Dir function as previously to simply test whether a filename is valid/existing (e.g., Sunday file doesn't exist, etc.), and skip over it if it's not valid.
Function GetFileNames(Optional FirstDay = vbFriday)
Dim filenames(1 To 7) As String
Dim i As Long
For i = 1 To 7
filenames(i) = Format(Date - (Weekday(Date, FirstDay) + i), "m.d.yy")
Next
GetFileNames = filenames
End Function
It seems that you want your search to start from yesterday instead of today. If so, you can try changing
ThursdayDate = Format(Date - (Weekday(Date, vbThursday) - 1), "m.d.yy")
into
ThursdayDate = Format(Date - (Weekday(Date - 1, vbThursday)), "m.d.yy")
and generalize it to other week days. In fact what it does now is that when it runs, say, on this Thursday, it looks up for the file of last Thursday...
I am trying to pull all data entries that are within a userform selected month and year. I can get the code to run fine when I hard code the year but I want the year to come off of a text box. I converted the Textbox value to an integer using Cint() and dim'd it to "Year" in my if statement. I can get it to work if I write Cdate("3/1/2016"), but I want see if there is a way to run it like: Cdate("3/1/Year"). I tried it this way and get a typematch error on the Cdate Im pretty new to VBA so excuse my stupidity.
Ignore the "Month" variable I was just using that to put a stop on the code and step it through to see if it would enter my if statement.
Thanks in advance.
My Code
Private Sub OKBtn_Click()
Dim Sales As Range
Dim Year As Integer
Dim Month As Integer
Dim i As Integer
Year = CInt(YearText.Value)
Set Sales = Worksheets("Sales").Range("A4")
i = 0
If Sales.Offset(i, 1).Value >= CDate("3/1/2016") And Sales.Offset(i, 1).Value <= CDate(" 3/31/2016 ") Then
Month = 1
End If
In order for the CDate to work, you need to seperate the stings inside the brackets to 2 parts
1.The constant, in your case "3/1/".
2.And the variable, CInt(YearText.Value).
Option Explicit
Private Sub OKBtn_Click()
Dim DDate As Date
DDate = CDate("3/1/" & CInt(YearText.Value))
' for debug only
MsgBox "Date entered is :" & DDate
End Sub
I'm knew to vb scripting for excel and cant seem to find code that will help do what i want. maybe its how im wording my search criteria.
Sheet 1 is an input sheet which saves data into sheet 2 every day. There is a cell that holds the current date.
So sheet 2 just collates and saves everything entered.
Each day there are several rows saved into sheet 2.
I need a button on sheet two that only selects the rows that have today's date and copies the content. I just need that data copied so i can then paste this into off clipboard into another application.
Can anyone help? im using office 2016.
Thanks
Excel VBA, How to select rows based on data in a column?
I believe this is something that would be useful for yourself since you are new to VBA code.
You will most likely need to supplement your code with the parts you ned, IE current date, only coping and not pasting and so forth.
I recommend google for those parts as it is widely avalible, I.E. VBA Excel "then what you are searching for"
Dim TodaysDate As Date
TodaysDate = Now
TodaysDate = Format(TodaysDate, "dd/mm/yyyy")
^ For instance will give you the current day in dd/mm/yyyy format
I leave the rest to you, hope this helps
I would loop through the rows in the second sheet and hide the rows not matching the date. So something similar to this:
Dim today As String
Dim Rows As Integer
Dim Sheetname As String
Dim Column As Integer
Sheetname = "Sheet2" 'Name of your second sheet
Column = 1 'Column with your date
today = Now
today = Format(today, "dd/mm/yyyy")
Rows = Sheets(Sheetname).UsedRange.SpecialCells(xlCellTypeLastCell).Row
Dim i As Integer
For i = 1 To Rows Step 1
If Sheets(Sheetname).Cells(i, Column).Value <> today Then
Sheets(Sheetname).Rows(i).EntireRow.Hidden = True
End If
Next i
Then you can copy the rows of today.
To show all rows again, simply use
Dim Sheetname As String
Sheetname = "Sheet2" 'name of your second sheet
Sheets(Sheetname).Cells.EntireRow.Hidden = False