I have created a pivot table that lists the number of visitors to a store on a given date. There are 3 columns of data, the date column and two columns of numbers representing the visitors. When I create a chart from this data I get a bar of data that represents dates before and after the range of dates that make up the data. I can suppress all dates that occur prior to the dates I want to view by using the command:
With Worksheets("Pivot Tables").PivotTables("Weekly Statistics").PivotFields("Date")
.PivotItems.Item(1).Visible = False
However, I can't find a way to suppress the dates that occur after today's date. This leaves me with a column on my bar chart that is blank and has the axis value ">3/27/2013". I can suppress it by actually typing this line:
.PivotItems.Item(">3/27/2013").Visible = False
but having to manually do this every time I update the sheet is laborious and makes the sheet unusable to anyone else.
I tried to create a variable that would update the value inside the () but I can't get it to work.
Dim t
t = Worksheets("Data").Range("i3").Value
.PivotItems.Item(t).Visible = False
(where i3 is a cell in the Worksheet("Data") that is a concatenation of the date; in this case the cell contents are ">3/27/2013" )
Thanks
You could try to use alternative filtering technique:
t="3/27/2013"
Worksheets("Pivot Tables").PivotTables("Weekly Statistics").PivotFields("Date").PivotFilters.Add Type:=xlBefore, Value1:=t
However, it is used as of Excel 2007.
If not working try to start with:
Worksheets("Pivot Tables").PivotTables("Weekly Statistics").PivotFields("Date").ClearAllFilters
Related
So I've created a graph to appear on this separate sheet titled "Report", and above it you can see that there are two dropdown boxes in which a user can select a specific date range. I would essentially like to link this user-specified date range to the range displayed on the graph. I'm having trouble figuring out how to link the source data for the chart to the date selectors.
The data for the chart is sourced from this separate sheet titled "Database", in which the data is chronologically ordered with corresponding Feed values. The goal is to match the dates selected by the user in the "Report" section to the dates in this "Database" sheet, and after finding the corresponding initial and start date, apply that same logic to the feed data to strictly display the feed data within that date range.
I am currently sourcing the chart data using this Macro, the xData and yData are linked to lists titled "Dates" and "FeedTonnage", which are basically tables I made out of the columns in the database. I'm not sure if the tables are even needed, but the database will continue to be updated overtime as more data will be coming in so I thought a table would've been useful for this.
So I've been trying to write a sub that sifts through the Date column to look for a date that matches the dates selected in the "Report" sheet. I'm doing this because I intend on using the cell address to get the corresponding data from the Feed column by replacing the column portion of the cell address with that of the Feed, and yeah, I'm kinda lost at this point so I could really use some input.
Instead of changing the data range of the chart, you can hide the rows of data outside the selected dates:
Worksheets("Database").Rows("3:100").Hidden = False
For i = 3 To 100
If Worksheets("Database").Range("A" & i).Value < Worksheets("Report").Range("B1").Value Or Worksheets("Database").Range("A" & i).Value > Worksheets("Report").Range("C1").Value Then
Worksheets("Database").Rows(i).Hidden = True
End If
Next i
The code above assumes the dates are in the range A3:A100, the start date is in B1 and the end date is in C1. Adjust the ranges as needed
I have a Table with a column that I added, that checks the date of that row against a formula.
The result of that formulae is TRUE or FALSE and a subsequent Pivot Table Sums a value in the TRUE rows. I Introduced it to get what is called a Rolling Total Income.
There are two formula and I want to swap from one to another using VBA.
The formula are:
=IF([#Date] = "", "", AND([#Date]>=EOMONTH(TODAY(),-13)+1,[#Date]<EOMONTH(TODAY(),-1)))
for the Rolling data.
=IF(AND([#Date] >=G1,[#Date] <=H1),"TRUE","FALSE")
for the Sum of Income between G1 and H1, the financial year start and end dates.
The VBA I have tried is as follows:
Set lo = Sheet2.ListObjects(1) 'Sheet2 is the Income sheet see Project list
lo.Parent.Activate 'Activate sheet that Table is on
Set lColName = lo.ListColumns(9)
lColName.DataBodyRange.Cells(1).Formula = [=IF(AND([#Date] >=G1,[#Date] <=H1),"TRUE","FALSE")]
Running the above errors and gives #VALUE in the first cell in that column, and doesn't ripple through the rest of the column.
What have I done wrong?
Try
lColName.DataBodyRange.Formula = "=IF(AND([#Date] >=$G$1,[#Date] <=$H$1),""TRUE"",""FALSE"")"
Thanks, those changes have sorted it.
One more refinement I am struggling with.
The IF test statement is testing a date against cells, $G1 and $H1 which I set up for ease of debugging. However I have another worksheet in the workbook where I store all the references/static data I use in the various Sheets and I have placed those dates there. In this Module, before the IF statement, I have set those dates against two variables.
startdate = Range("I2").Value
enddate = Range("J2").Value
I now want to use those in the IF statement but cannot get the correct syntax!
This just errors:
"=IF(AND([#Date] >= startdate,[#Date] <= enddate),""TRUE"",""FALSE"")"
How should I write it?
Thanks
I have a form that is supposed to show the total sum of different numeric values between two dates, a start date and a finish date. For this, I thought the best option would be to use the SumIfs WorkSheetFunction. However, after trying to code this, the function is not working properly. I am not sure of what is wrong. If I type the exact same formula on the worksheet that has the table with my sample data, it works perfectly.
So, the form I designed is the following:
A second label and textbox will be added for the finish (or end) date. However, I thought it would be better to do that once I get the code to work with a single date in the beginning. The textbox where the user will insert the start date is called tbxDate and the textbox that will show the resulting sum is called tbxBalance. The button that triggers the SumIfs functions is called cmdCalculate.
Also, the table that stores the data (which only has one row of data so far for testing purposes) is this one:
The table name is Sales, and the worksheet name is SalesWS. I thought the code should be pretty simple, unless there is something I am missing. What I did was:
Private Sub cmdCalculate_Click()
Set SalesRange = Worksheets("SalesWS").Range("Sales[TOTAL]")
Set DatesRange = Worksheets("SalesWS").Range("Sales[DATE]")
tbxBalance = Application.WorksheetFunction.SumIfs(SalesRange , DatesRange , ">=" & tbxDate)
End Sub
The issue is that the >= part of the criteria is failing. I only get proper results using only the greater than or less than conditions. For example, if I enter the date 09/08/2020 in the textbox the result in the balance textbox is 0, but if I enter the date 08/08/2020 or anything before it works. It just ignores the condition to sum the values if the date is equal to what is entered. It only works with dates greater or less than what the user inputs in the textbox, excluding the chosen date.
I already checked that the column with the dates in the table is formatted properly.
The version of your code given below should work provided your DATE range contains true dates and tbxDate contains a string VBA can recognise as a date.
Private Sub cmdCalculate_Click()
Dim Fun As Double
Set SalesRange = Worksheets("SalesWS").Range("Sales[TOTAL]")
Set DatesRange = Worksheets("SalesWS").Range("Sales[DATE]")
Fun = Application.WorksheetFunction.SumIfs(SalesRange, DatesRange, ">=" & CLng(CDate(tbxDate.Value)))
tbxBalance = Format(Fun, "#,##0.00")
End Sub
Remember that tbxBalance will cotnain a text string, not a number. Use Excel's NUMBERVALUE function to convert the formatted number you have in tbxBalance after the above code back to a number you can calculate with.
looking through the forum and can't find what I need. I have 100+ sheets with unique sheet names and data in column B. Column B will contain various END DATES. some sheets will have 1 or 2 end dates, others have upwards of 30 end dates. . I would like to create a summary page containing a table that will update itself to show all sheet names that have END dates in column B expiring within the next 30 days. is this something that requires coding? or use of the excel indirect formula with maybe a vlookup wrapped around it?
Private Sub ChkEndDates()
Dim ws As Worksheet
Dim cell As Range
Dim rowCount as Long
For Each ws in Worksheets
If ws.Name <> '"summary page" Then
rowCount = WorksheetFunction.CountA(ws.Range("B:B"))
For i = 1 To rowCount
If (ws.Cells(i, 2).Value - Date < 30) And (ws.Cells(i, 2).Value > Date) Then
MsgBox ws.Name
'And maybe push into the summary page
End If
Next i
End If
Next ws
End Sub
Neither VLOOKUP nor INDIRECT are required for this problem.
Assuming your dates in the B columns are in Excel's serial number format, this formula will calculate the amount of cells in the B column of Sheet2 that are within 30 days from today's date:
= SUMPRODUCT((Sheet2!B:B>=TODAY())+0,(Sheet2!B:B<=(TODAY()+30))+0)
You can just duplicate this formula for however many sheets you need, e.g.
= SUMPRODUCT((Sheet2!B:B...))+SUMPRODUCT((Sheet3!B:B...))
EDIT
Per #Jeeped's comment, it is recommended to narrow down this range (B:B) just to the end of your data. (e.g. if you have at most 30 rows of data, change to B1:B30)
For completeness, here's how you would do this using PowerQuery/Get & Transform if you had Excel 2013 or later.
First, you would turn each of the data areas in your workbook into Excel Tables (aka ListObjects), by selecting them and either using the Insert>Table command from the ribbon, or simply by using the keyboard shortcut [Ctrl] + [T]. Ideally you would give them all a name that denotes what they are. (I've used the prefix "Input_" and then a running count, because later this 'handle' will help me to ignore any Tables that I don't want in my end result, simply by seeing if it's name is prefixed with "Input_").
Then from the Data tab, select New Query>From Other Sources>Blank Query:
A mysterious looking UI called the PowerQuery window will open with nothing much of interest in it. If you type =Excel.CurrentWorkbook into the formula bar and press Enter, then a list of the various Tables in your workbook will populate in that window, as shown below. And if you click that twin arrow icon to the right of the Content column, a menu will appear that lets you expand those tables to include the actual columns in each of them, and bring them into the PowerQuery window:
And here's how that data dump looks, when you push OK:
This next bit is only required if you have other Tables in your workbook already that you don't want to show in your end mashup. In the screenshot below, I'm filtering the result set to only include tables with the Input_ prefix:
And then I'm going to change the data type of that DateTime column to a simple Date, by selecting the column concerned, and then choosing Data Type>Date from the Transform tab.
Then I'm going to select Close and Load To from the menu at top right:
..and then select the "Only Create Connection" and "Add to Data Model" options from the resulting dialog:
Now back in Excel, I create a PivotTable, and leave the "Use this workbook's Data Model" option checked:
...which brings up a slightly different looking PivotTable Fields List than you usually see:
I now add the Name (Table Name) and End Date fields to my Pivot, and set a date filter to just show dates within the next 30 days:
And here's the end result, a PivotTable that shows just those tables with end dates within the next 30 days:
The beauty of this approach is that if you later add more tabs with more input tables, then provided you prefix them with "Input_" then they will automatically appear next time you refresh the PivotTable. And furthermore, instead of having a report that merely tells you which tabs have applicable End Dates, the PivotTable also tells you which individual records in those tabs are involved.
There's more stuff I would do along the way that I haven't shown, such as give the columns friendlier names by ditching the "Content." suffix, and I'd probably write a simple macro to automatically refilter the PivotTable based on 30 days from the current date. But this at least shows you the benefits of upgrading to Excel 2013 and using PowerPivot/Get and Transform to radically automate tasks such as this.
Starting with screenshot:
http://i.imgur.com/Isj9MER.png
(I'm a new user, can't post images)
Working for a call center. We have a program that tracks our time spent in various phone states (so when we're on calls, out to lunch, etc) that can export data for a given team and date range as a CSV.
I'm working on automating this report. The way it works is that the team lead will pull the CSV, copy-paste into another tab, and then I've got a bunch of array formula If functions and Indirect references to pull all the data as shown. The data analysis and everything is working great.
My problem is the graph. Right now, I've got column B with an If function that either outputs the agent's email (which is how the system tracks it) or "" if all emails have been used. The rest of the columns have If(B2="","", [relevant formula]). That way, we can have all the team leads with various (and fluctuating) team sizes use the same report with a simple copy-paste.
My problem is the stupid bar chart. It pulls data from rows 2-32 (A2:A32). Our current largest team is 28, and I left room for new hires showing up soon. My problem happens when I use data from one of our smaller teams. As you can see, even though the blank rows are filled with "" in every cell, it's still displaying those rows. In the chart. This means that with the smallest team (shown), the chart is half wasted whitespace.
Is there a way to make the column chart only show rows that have actual data in them?
One thing I tried was putting an Indirect reference for Series Values. So I had a cell (AA1) with {=MAX(IF(B2:B31="","",ROW(B2:B31)))}. That outputs the row number of the last non-blank row. Then for the Series Values I put =Indirect("Report!A2:A"&AA1), but Excel gave me an error saying the function was not valid. I guess you can only have an actual range (and not a formula) in the data input for a chart.
Excel 2016, by the way.
I come up with three possible solutions for this problem.
Convert your data table to a pivot table and use a pivot chart (currently only available in Windows version, sorry if you are using a Mac).
Use a bit of VBA to hide the empty rows.
Use a bit of VBA to modify the data displayed on the chart.
Sample Data Setup
Although you provided a screen shot of your data, it is not simple to convert that into a test case to demonstrate the three solutions. Therefore, I threw together this very simple set up.
Column A contains a list of possible "users".
Cell D1 is a user entry to change the contents of column B and C.
Column B contains the actual "users". It is calculated with =IF(A2<=$D$1,A2,"")
Column C contains the data that goes with the "users". It is calculated with =IF(B2<>"",10,"")
A chart is added to the sheet.
Below is a screenshot of the sample setup, where all potential users are included. (Note: It is Sheet1)
Below is a screenshot of the sample setup, where only potential users A through E are included.
The white space in the second image is the problem we are trying to address.
SOLUTION 1: Make a pivot table of the data
Select all of the pertinent data, in this case B1:C12.
Select Insert -> Pivot Table
In the Create Pivot Table dialog, make sure "New Worksheet" is selected, and click OK.
On the Pivot Table, place "User" field in Rows, and "Total" field in Values. Select the Value Field Settings... for the "Total" field and make sure it uses Sum.
In the Pivot Table, select the Row Labels drop down, Label Filters, Greater Than... . Type "" into the dialog and select OK.
From Pivot Table Tools -> Analyze, select PivotChart. Choose Bar Chart from the dialog.
Below is a screen shot of the Pivot Table.
On the tab with the data, change the last potential user from E to G. On the Pivot Table, refresh the data.
Below is a screen shot of the refreshed pivot table.
SOLUTION 2: Use VBA to hide empty rows
The below code is attached to a button made visible on the worksheet. (n.b. There are other ways to activate the code such as change events, but this will depend on a number of factors outside the scope of this answer).
Sub HideRows()
Dim AllCatRange As Range
Set AllCatRange = Worksheets("Sheet1").Range("B2:B12")
Dim iLoop As Long
For iLoop = 1 To AllCatRange.Rows.Count
If AllCatRange.Cells(iLoop, 1) = "" Then
AllCatRange.Cells(iLoop, 1).EntireRow.Hidden = True
Else
AllCatRange.Cells(iLoop, 1).EntireRow.Hidden = False
End If
Next iLoop
Set AllCatRange = Nothing
End Sub
Below is a screen shot of the data tab with the button added.
After clicking the button, it now looks like this ...
This code will expand rows when they contain data, and collapse rows when they do not.
A potential problem with this approach is that expanding/collapsing rows will change the size of the chart, if the chart lays over those rows.
SOLUTION 3: Use VBA to modify the chart
The below code is attached to a button, and used to modify the chart after the source data is changed.
Sub ModifyChart()
Dim AllCatRange As Range
Set AllCatRange = Worksheets("Sheet1").Range("B2:B12")
Dim lastRow As Long
lastRow = 1
Dim iLoop As Long
For iLoop = 1 To 11
If AllCatRange.Cells(iLoop, 1) <> "" Then
lastRow = lastRow + 1
End If
Next iLoop
Dim PlotCatRange As Range
Set PlotCatRange = Worksheets("Sheet1").Range("B2:B" & lastRow)
Dim PlotSerRange As Range
Set PlotSerRange = Worksheets("Sheet1").Range("C2:C" & lastRow)
Worksheets("Sheet1").ChartObjects(1).Chart.FullSeriesCollection(1).XValues = "=Sheet1!" & PlotCatRange.Address
Worksheets("Sheet1").ChartObjects(1).Chart.FullSeriesCollection(1).Values = "=Sheet1!" & PlotSerRange.Address
Set AllCatRange = Nothing
Set PlotCatRange = Nothing
Set PlotSerRange = Nothing
End Sub
Below is a screenshot of the data tab with the new button in place.
Below is a screenshot of the tab after clicking the button.
Wrap up
My personal preference is to use VBA to modify the chart after the data is modified, as this reflects what you would do manually.
I found a solution! Thanks largely to this page. Here's what I did:
I created made a named range using this formula: =OFFSET(Report!$B$1,1,0,COUNTIF(Report!$B$2:$B$30,"<>-"),1)
For that to work, I had to change all the empty cells to output "-" when empty in stead of "". I couldn't get COUNTIF to accept "<>""" or "<>" or any other weird tricks I tried. Using "-" was easier.
That makes a dynamic named range that changes size as I put data into the sheet. I named a similar range for everything I'm trying to chart (Approved Status, Call Ready, Not Ready). The chart was able to accept those names and now it's dynamically sized. If I only have three agents on the sheet, it shows three huge bars. With twenty, it shows twenty bars (exactly what I was looking for).
One other tip: I changed my first row to output "" when empty, so that COUNTIF(Report!$B$2:$B$30,"<>-") always returns at least 1 (otherwise you get annoying errors because you have a named range referencing a 0-length array).