Looking for a custom solution to copy data from one workbook to another - vba

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

Related

segregate the data based on their own value

I have data where list is dynamic. I would like to segregate the data base on their own value.I am unable to predict the exact value coming every time. Example : - This time I got company code as 1959809 and 1960574. I would like to filter data based on company code and would like to paste it in new workbook. This number will get change every time. Next time the company code may be 1960574 and 1963665.
I am thinking that we need to group the company code value so that we can have it in variable. However, I am unable to get the logic.
I am not getting any logic to do so. Hence, I don't have anything to show.
We should get two or more workbooks based on company code along with respective data.
Assuming your data has first column as 'Company Code' and starts from the first row of sheet, Following code will help you achieving your goal:
Sub ExportFilteredData()
Dim Codes As String, CodesArray, Code
Dim Wb As Workbook, CurSht As Worksheet
'Get the company codes from user as comma separated values
Codes = InputBox("Enter Company codes separated by comma")
CodesArray = Split(Codes, ",") 'Split company codes to array
'Save the data sheet reference and remove any applied filter
Set CurSht = ActiveSheet
CurSht.AutoFilterMode = False
'Filter data for each company code and save as new workbook
For Each Code In CodesArray
'Change the 'Field' value to the actual 'Company Code' column number
CurSht.Range("A1").AutoFilter Field:=1, Criteria1:=Trim(Code)
Set Wb = Workbooks.Add
CurSht.AutoFilter.Range.SpecialCells(xlCellTypeVisible).Copy Wb.Sheets(1).Range("A1")
'Change the path and filename as per your requirement
Wb.SaveAs ThisWorkbook.Path & "\" & Trim(Code) & ".xlsx"
Wb.Close False
CurSht.AutoFilterMode = False
Next
End Sub

VBA - Moving large number of records - some records missing

I have a data set of around 1500 sales records. I have written a macro, which would create product category specific work books, which would have an individual work sheet for each product in the product category.
The macro is working as expected, but I have found out that it is consistently ignoring some products. I put debug statements to see if I am getting zero records when I filter based on the product code (since I use this selection to paste the records to a separate work sheet). The selection seems to be working fine, as I get the number of rows selected.
A pattern I saw was that the product codes which were having zero records were generally the first ones or the last ones to get processed before or after a file operation (either I open a category specific work book, or I am closing a work book). But even here, the table header was copied to the individual work sheet. Only the data rows were getting ignored.
Is there a chance where the macro is processing the records too fast, while there is some time lag in doing File I/O operations (which makes a few records to get ignored)?
I am attaching the code, which I have used for looping
'loop through each row and get the product id and the category (Ann & Bnn).
' Dim catWorkBook As Workbook
oProductCat = "0" 'the initial value set as 0, which would NEVER be a category
With wkScrap 'this is a rough sheet which has the product items and categories
For i = 2 To lProdRow
cProductCode = .Cells(i, 1).Value
cProductCat = .Cells(i, 2).Value
'FILE OPEN: will need to open a category specific .xls file
If (StrComp(cProductCat, oProductCat) <> 0) Then
'save the existing workbook
FileIO.CloseExcelFile oProductCat, catWorkBook
Set catWorkBook = Nothing 'clear all traces of the old worksheet
Set catWorkBook = CreateBlankWorkBook()
oProductCat = cProductCat
End If
'COPY DATA: Filtering on product code, and then moving it into a new
'worksheet
CopyCategoryToWorksheet cProductCode, catWorkBook
If i = lProdRow Then
'we are at the end of the loop. Proceed to close the current
'workbook
FileIO.CloseExcelFile oProductCat, catWorkBook
End If
Next
End With
Here is the function which does the actual copying
Private Sub CopyCategoryToWorksheet(prodCode As String, catWkBook As Workbook)
'check for a meaningful prod code
If (Trim(prodCode & vbNullString) = vbNullString) Then
Exit Sub
End If
Dim wkRData As Worksheet
Dim rRData As Range
Dim rDataMaxRows As Integer
Set wkRData = SalesReport.Sheet1
'We know that we have to create a work sheet for this product code.
'Let us do that first.
Dim prodCatSheet As Worksheet
catWkBook.Activate
Set prodCatSheet = catWkBook.Sheets.Add(After:=catWkBook.Sheets(catWkBook.Sheets.Count))
prodCatSheet.Name = prodCode
wkRData.Activate 'for this sub routine, all processing is happening on the raw data sheet
rDataMaxRows = Cells(rows.Count, 1).End(xlUp).Row
Set rRData = Range("A1:H" & rDataMaxRows)
rRData.AutoFilter 3, Criteria1:="=" & Trim(prodCode)
rRData.Select
Selection.SpecialCells(xlCellTypeVisible).Select
Selection.Copy
'activate the newly created sheet, and paste all the selected rows there
prodCatSheet.Activate
prodCatSheet.PasteSpecial
Set wkRData = Nothing 'just clear some memory
End Sub

Creating Daily worksheets, archiving previous weeks worksheets

I am trying to figure out how to archive week old worksheets.
A little background on my project:
I create two new worksheets every day that house daily report summaries and calculations that I review on a daily basis. As of now, there are way too many worksheets open in the one excel file so it takes forever to open and send to people.
Ultimately, I would like to figure out how to save any worksheets that were created the previous week to another file. I would like to save these all in a seperate (single) workbook, or somehow create a folder to house each workbook for each day that week.
So for example, I create 10 worksheets for the current week (2 for each day of the week, Mon - Fri). Then, when I come in the following monday and start creating the worksheets for that week, the old sheets would be put into another workbook.
The code I currently use to create the worksheets every day:
TD = Format(Date, "yyyy.mm.dd")
On Error GoTo Make_Sheet
Sheets("Open_" & TD).Activate
Sheets("Open_" & TD).Select
Cells.Select
Selection.Delete Shift:=x1Up
Exit Sub
Make_Sheet:
Worksheets.Add(After:=Sheets("Print")).Name = "Open_" & TD
ActiveSheet.Name = "Open_" & TD
With ActiveWorkbook.Sheets("Open_" & TD).Tab
.Color = 5296274
.TintAndShade = 0
End With
The code will check to see if the current date's worksheet already exists (using the date as the title of the worksheet), if it does it clears it. Otherwise it will create the new worksheet. It will also colour code the tab (since I create 2 each day). I have another identical set of code to create the second daily worksheet.
Thanks in advance,
-Tuques
Here is a macro to copy all sheets to a new workbook, save and close the new workbook. Delete all sheets but the first one and then clear the contents of the remaining sheet.
Not sure what sheets you want to preserve.
Sub New_week()
NWeek = MsgBox("Is this the start of a new week?", vbYesNo + vbQuestion)
If NWeek = 6 Then
Dim fname As String
'Create new Workbook name.
'Add path if you want it in a specific folder
fname = "Week" & Format(Date, "yyyy_mm_dd") & ".XLSX"
'copy all sheets
Sheets.Copy
'save to new file
With ActiveWorkbook
.SaveAs FileName:=fname, FileFormat:=xlOpenXMLWorkbook
.Close SaveChanges:=False
End With
'Delete all sheets except first
Application.DisplayAlerts = False
Do While Worksheets.Count > 1
Worksheets(2).Delete
Loop
Application.DisplayAlerts = True
'Clear contents of first sheet
Sheets(1).UsedRange.Clear
End If

Copy from one Excel Application To Sheet Without Changing Dates VBA EXCEL

I am trying to copy an entire sheet from one application sheet to another open one with the following code
'Open Application
MsgBox "Select Report"
Dim my_FileName3 As Variant
my_FileName3 = Application.GetOpenFilename("Excel Files (*.xl*)," & _
"*.xl*", 1, "Select ManMan File", "Open", False)
If my_FileName <> False Then
Workbooks.Open Filename:=my_FileName3
End If
'Set Active
var3 = ActiveWorkbook.Name
'Copy Everything
Dim lastRow3 As Long
lastRow3 = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
ActiveSheet.Range("a1:z" & lastRow3).Copy Destination:=Workbooks (var1).Sheets("Sheet4").Range(Var1R)
'Close Worksheet
Workbooks(var3).Close False
This code above works but the problem is the dates have been completely changed.
Any idea what I might be doing wrong? Ignore the empty row.
The difference in the dates can be explained by inconsistent use of the date system between the two workbooks. One will be using the 1904 date system, and one won't be:
If the destination workbook is using the 1904 date system, you will need to subtract 1462 from each value copied in order to convert it back to the same date that you started with.

Excel VBA to filter Pivot Table and Pivot Chart for previous day - Pivot Filter Field

Here is my problem, every bit of code, every alteration, every type, doesn't work. I'm using Office 360 at my work site (up to date), so it's excel 2016 and VBA 7.1.
What I'm looking to do is automate our end of shift reports. Here's the process:
We enter data into an excel sheet (Log) every hour. At the end of the day, at 5:00 AM, we save and close that log, open another excel sheet that IMPORTS the data into power pivot, and displays it on a PivotTable (formatting for printing for our bosses), and we choose the filter for the previous date using the filter drop down, and print it. We do this with three (3) reports: 2 PivotTables, and 1 PivotChart. Power Pivot imports ALL of the data from the Log sheet to reformat it for printing.
I've successfully managed to get and rewrite the code (beginner at this) for the automation process of: auto saving the log, closing the log, opening the Report workbook, refreshing the data, and printing the data, then closing the report. The only part I'm now missing is the auto-filtering.
The code I've tried is vast, but here's an example of what I've tried recently (I've erased and re-copied so many codes...)
Sub Filter_PivotField()
'Description: Filter a pivot table or slicer for a specific date or period
'Source: excelcampus.com/vba/filter-pivot-table-slicer-recent-date-period
Dim sSheetName As String
Dim sPivotName As String
Dim sFieldName As String
Dim sFilterCrit As String
Dim pi As PivotFields
'Set the variables
sSheetName = "EOS Report"
sPivotName = "PivotTable1"
sFieldName = "Date"
sFilterCrit = "xlDateYesterday"
'sFilterCrit = ThisWorkbook.Worksheets("EOS Report").Range("O1").Value
With ThisWorkbook.Worksheets(sSheetName).PivotTables(sPivotName).PivotFields(sFieldName)
'Clear all filter of the pivotfield
.ClearAllFilters
'Loop through pivot items of the pivot field
'Hide or filter out items that do not match the criteria
For Each pi In .PivotFields
If pi.Name <> sFilterCrit Then
pi.Visible = False
End If
Next pi
End With
End Sub
To no avail....
When I record a macro doing the manual filter, I get this:
Sub manualfilter()
'
' manualfilter Macro
'
'
ActiveSheet.PivotTables("PivotTable1").PivotFields( _
"[Bi-Hourly Report].[Date].[Date]").VisibleItemsList = Array( _
"[Bi-Hourly Report].[Date].&[2016-09-28T00:00:00]")
End Sub
But it fails when I try to re-run the same macro that I just recorded (after changing the date back). I've enabled and disabled multiple selection option, etc.
Not to mention, trying to auto-filter a chart is a nightmare because tables, yea there's tons of articles on it, but charts? not much comes up on researching.
Here's images of the filter button, because almost everything I've researched is to sort the COLUMN of the Table, not the filter itself with a PivotTable.
Table Filter
Chart Filter
I cannot post the actual excel spreadsheets as they are proprietary property of the company, but I can replicate the format with false data if needed.
check this out.
Dim prev_date As String
prev_date = Month(Date - 1) & "/" & Day(Date - 1) & "/" & Year(Date - 1)
Thisworkbook.Sheets("Sheet1").Activate
'change this line with your sheet where pivot table is present. Change Sheet name.
ActiveSheet.PivotTables("PivotTable1").RefreshTable
ActiveSheet.PivotTables("PivotTable1").PivotFields("Date").CurrentPage = prev_date