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

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

Related

Excel VBA Loop Through a PivotTable and perform calculation

I have a PivotTable that automatically refreshes every time I refresh a data set to our mySQL database in our office.
My Excel file launches a query against the mySQL database and returns a data table, and I have two PivotTables on separate sheets that will automatically update every time that is done. My code for that is below:
Sub UpdatePivots()
' This sub is intended to update all pivot charts in the by switching to the appropriate
' worksheet, locating the appropriate pivot table, and updating them.
Dim ws As Worksheet
Dim PT As PivotTable
For Each ws In ActiveWorkbook.Worksheets '<~~ Loop all worksheets in workbook
For Each PT In ws.PivotTables '<~~ Loop all pivot tables in worksheet
PT.PivotCache.Refresh
Next PT
Next ws
End Sub
What I am looking to do calculate a YIELD for some of the fields in the Pivot Table. The table currently looks like this below:
As you can see, I added in the "YIELD" column automatically and simply did an:
=GETPIVOTDATA("Pass / Fail",$B$5,"Job ID","Job 1","Pass / Fail","Pass")/GETPIVOTDATA("Pass / Fail",$B$5,"Job ID","Job 1")
Ideally, what I would like to do is add to my UpdatePivots() macro to automatically calculate the yield (Pass / Grand Total) for each of the rows listed.
This table is subject to change in size - sometimes I am looking at only 3 jobs in a given month (like September so far), other times my boss wants me to run this report for an entire year where I can have an upwards of 100 jobs. So I would like to use some pseudo code that might look like this:
Cell F6.Text = YIELD
<Apply Pivot Table Formatting to Cell F6>
for each row in pivottable {
Cell Fx.Value = Pass / Grand Total
}
Can anybody help me do that? I have tried brainstorming on paper, but don't even know where to start.
PS - How can I get the Pivot Table to stop that terrible formatting, and to keep my grayed cells? I want to eventually add in charts.
Thank you!!
The following code satisfies my need:
Sub CalculateYield()
k = Cells(Rows.Count, 2).End(xlUp).Row
For r = 9 To k
Cells(r, 6).Formula = "=" & Cells(r, 3).Address(False, False) & "/" & Cells(r, 5).Address(False, False)
Next
End Sub

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

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

VBA: Finding the row number by looking up a user defined value (date)

I am trying to use VBA to look up the row value that corresponds to a user defined date on one of my work sheets so that I am able to edit all data on that row.
As a bit of context:
I have several time series data sets that all have different start and end dates with a good portion of overlap in the middle. I want to chart these using user defined date parameters, however, because of non-uniform start dates, the chart is impossible to dynamically rebase.
I was hoping to use a macro to clone the data on one sheet, overwrite the line of values that corresponds to the user defined start date, and then calculate return values based on percentage change figures (I already have in a different sheet).
If I can dynamically o/w the row that corresponds to the UD start date of the date range, I can replace it with a one and all my calculations will effectively rebase.
Any and all feedback would be great!
EDIT
Lucas,
I am having two issues; firstly, what I have inexpertly cobbled together doesn't work when I protect the sheets (not insurmountable); secondly, it doesn't work :). Here is my work:
Sub Rebase()
Dim UDStartVal
Dim UDStartLoc As Range
Dim UDRow As Integer
'
' Rebase Macro
' A macro to rebase the chart to the user defined start date.
'
'
Sheets("Cumulative Monthly Returns").Select
Cells.Select
Selection.Copy
Sheets("Chart Numbers").Select
Range("A1").Select
ActiveSheet.Paste
' Lookup to change the value of the cells corresponding to the user defined start date to 0, effectivley rebasing the portfolo.
Worksheets("Cumulative Period Returns").Activate
UDStartVal = Cells(4, 2).Value
Set UDStartLoc = Range("A:A").SpecialCells(xlCellTypeVisible).Find(UDStartVal)
Set UDRow = UDStartLoc.Row
Stop
End Sub
Here's some code that I use to find the row of an entry based on quote numbers on a sheet that gets resorted and re-filtered constantly.
Private Sub FindQuote(partNum as String)
Dim quoteRow as Range
Set quoteRow = Range("A:A").SpecialCells(xlCellTypeVisible).Find(partNum)
then when I want to do something that uses the range of that row I use quoteRow.Row
If Not quoteRow Is Nothing Then
quoteNum = Cells(quoteRow.Row, "P").Value
Cells(quoteRow.Row, "Q").Value = "Found"
Else
MsgBox "No quote was found"
End If
End Sub
Did you need help with the part where you clone your sheet?

excel real time refresh of filter

In my Pivot Table in excel, I have a field List about the due date of some reports.
For example, 10/5/2016
My problem is, every day I have to choose the date so that I can see the report code, I don't want it to be this. What I want is, everyday I open the excel, the filter will automatically change from 10/5/2016 to 11/5/2016.
What function / VBA should I use?
Helps
If you want a VBA solution, add the following to the ThisWorkbook code.
Private Sub Workbook_Open()
Dim tDay As Date, pf As PivotField
tDay = Date
Set pf = Sheets("name of worksheet").PivotTables("pivot table name").PivotFields("insert the name of your filter here")
pf.ClearAllFilters
pf.CurrentPage = tDay
End Sub
Change the sheet name, pivot table name and the name of the filter.
If you need to do more VBA manipulation of pivot tables I suggest reading the following http://www.thespreadsheetguru.com/blog/2014/9/27/vba-guide-excel-pivot-tables.

Automation 31 templates or 1 template

am producing an excel report where I bring in data for one country via a data connection and then run a macro that refesh pivots and other sheets with that data and then closes and saves the Excel report for that country. For example Germany . I have then another 31 templates for other countries where the same process happens. The differences between the 31 templates is that the database sql query for the data connection ( bring records for Germany ) and the filename that it is saved as like Report_Germany .
In SSIS, I am using a process task that calls a vbs script which simply opens an excel file and runs a macros for each country . Now I do not want to create 31 different SSIS tasks.
Anyway I could use 1 Template and produce the required 31 Excel Reports in the same directory ?
Yes, it is possible to use a single temple to create multiple reports.
All your pivot tables need to have a report filter equal to the country and all the data needs to be retrieved into one workbook.
Then you can loop through the countries setting the filters each time and saving the workbook as with a separate country name.
Listed below is some basic code to achieve this.
Sub Update_Pivot_filter()
Dim StaticArray(1 To 3) As String
Dim strName As String
Dim lCount As Long
StaticArray(1) = "Germany"
StaticArray(2) = "France"
StaticArray(3) = "Italy"
For lCount = LBound(StaticArray) To UBound(StaticArray)
ActiveWorkbook.Sheets("Sheet1").PivotTables("PivotTable1"). _
PivotFields("Name").CurrentPage = StaticArray(lCount)
' Change report filter on a pivot table
ActiveWorkbook.RefreshAll
' Refresh all pivot tables
ActiveWorkbook.SaveAs Filename:= _
"C:\Temp\Report_" & StaticArray(lCount) & ".xlsx", _
FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
' Save the file with a name matching the filter name
MsgBox StaticArray(lCount)
Next lCount
End Sub
The downside of this approach is that each workbook contains all your data.