I have a pivot table with the following columns:
item_number, job_number, description and qty.
I would like to have VBA code take the input of a cell, A5, to automatically sort through the job_number column of my pivot table and find the entries that have the job_number found within A5.
The data set is very large, so it is not a wise idea to sort through using PivotItems.
I have a file that does exactly that. I have a cell which isn't part of the pivot table but acts like a filter field for the pivot table.
I put a script into the Worksheet_Change event to watch that cell for changes and a sub which swaps out the filter on the pivot table to match the cell value.
The Worksheet_Change event is basically like
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Me.Range("A5")) Is Nothing Then Call FilterChanger
End Sub
And the FilterChanger sub is basically like
Private Sub FilterChanger()
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Dim FilterText as String
FilterText = Me.Range("A5")
With Me.PivotTables("MyPivotTable")
.ManualUpdate = True
.PivotFields(3).ClearAllFilters
.PivotFields(3).PivotFilters.Add Type:=xlCaptionContains, Value1:="zzzzzzzzzzzz"
'Filter out all results to prevent table updating when clearing filters
.PivotFields(5).ClearAllFilters
'now that there is another filter, there isnt any lag while the table tries to load all the unfiltered data
.PivotFields(5).PivotFilters.Add Type:=xlCaptionEquals, Value1:=FilterText, Value2:=FilterText
.PivotFields(5).ShowDetail = True
.PivotFields(3).ClearAllFilters
.ManualUpdate = False
End With
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
Application.EnableEvents = True
End Sub
In this code PivotFields(3) is any pivot row field that is in the table other than the one you intend to filter. and PivotFields(5) is the field that I am targetting with my filter. You can put column names instead of a number when referring to your fields, but I just prefer numbers.
In my file, the source data for the pivot table is 20k rows and growing, so I found that whenever I did .ClearAllFilters the workbook would pause for ~10 seconds while the pivot table attempted to load all 20k rows. To fix that issue, I put in a temporary filter in another field which will prevent any rows from loading while I swap out the filter in the intended field. I chose zzzzzzzzzzzz in PivotField(3) because it will always return 0 rows.
Sub Macro1()
' in A1 there is the value for sorting
' if you want to show the whole table again run only the "select all" part (line 2):
' Field value == Column (right now column 2); Criterial == Filter Value (value of cell A1) ; change Table name to yours
ActiveSheet.ListObjects("Table1").Range.AutoFilter Field:=2, Criteria1:=Range("A1").Value
' "Select All -- to show whole table again de-comment following line
'ActiveSheet.ListObjects("Table1").Range.AutoFilter Field:=2
End Sub
Hope this is what you are looking for.
Related
enter image description hereI have an Excel workbook that runs a macro and in the end displays everything in a pivot table
I am trying to add a msgbox when my pivot table has an empty cell (at the end of my macro)
I already did the conditional formatting version(color blank cells red) and it works fine, but the client wants a msgbox to alert him.
I found a IsEmpty command that should work but I cant seem to make it look only inside said pivot table.
Here is what I tried:
Sub IsEmpty()
If IsEmpty(ActiveSheet.Range("PivotTables(1)")) = True Then
'Cell A2 is not blank
MsgBox "Cell A2 is empty"
Else
End If
End Sub
I'm sure the way my If statement is written is false. Just cant seem to find the right syntax.
Thanks in advance
Picture added; I want the macro to target pivot's C column. However, you cant know which cell will be empty or how long the list will continue.
And if just make Excel check a broad spectrum(c2:c300), there will always be en empty cell after the pivot table is finished.
There might be a loop you can create but its way over my current skill set.
The pivot table's name is "PivotTable2"
Is there a to search only in the pivot table's column c for empty cells?
Please consider the capabilities of the function below. It will return True or False depending upon the count of items in columns A and C. In column A text, number or function is counted. In column C there must be a number in each cell. If both counts are the same the function returns True. Either count can be further refined if there are exceptions which the current function doesn't correction evaluate.
Function IsComplete() As Boolean
' 025
Dim Rng As Range
With ThisWorkbook.Sheets("PivotTables(1)") ' change to suit
' set a range from A3 to end of column A
Set Rng = .Range(.Cells(3, "A"), .Cells(.Rows.Count, "A").End(xlUp))
End With
With Application.WorksheetFunction
IsComplete = (.CountA(Rng) = .Count(Rng.Offset(0, 2)))
End With
End Function
You can use code to call this function and display a message box for True and another one if the function returns False. The code can be hitched to a button on your sheet, anywhere in your workbook.
Sub CommandButton1_Click()
Dim Txt As String
If IsComplete Then
Txt = "The pivot table was created without mistakes."
Else
Txt = "Some data are missing in the pivot table."
End If
MsgBox Txt, vbInformation, "Action report"
End Sub
You can also call the function as a UDF and display True or False in a cell of any sheet in your workbook. The UDF call would be like =IsComplete(). You might also embed the UDF call in an IF condition and display another text on your worksheet.
=IF(IsComplete(),"All's well","Missing Item")
In fact, you could slightly modify the function to return the difference between one count and the other and display "1 item missing". The possibilities are endless because the function is so versatile.
I have a filter procedure with which I want to skip filtering certain columns if it doesn't contain relevant data. This is my code followed by my description and question:
Sub FilterData()
'First I select my values in a pivot table in my Dashboard sheet.
' Cell references P7, P8 and P9 are fields in this pivot;
Myvalue1 = Sheets("Dashboard").Range("P7")
Myvalue2 = Sheets("Dashboard").Range("P8")
Myvalue3 = Sheets("Dashboard").Range("P9")
Application.ScreenUpdating = False
'Next I go to my dataset that the pivot is based upon in another sheet
' to filter the data according to my selected values from before.
Sheets("Data").Visible = True
Sheets("Data").Select
'First I clear existing filters if applicable, then I start to sort the data.
If ActiveSheet.AutoFilterMode Then ActiveSheet.AutoFilter.ShowAllData
ActiveSheet.Range("$A$1:$BR$30000").AutoFilter Field:=12, Criteria1:=Myvalue1
ActiveSheet.Range("$A$1:$BR$30000").AutoFilter Field:=66, Criteria1:=Myvalue2
ActiveSheet.Range("$A$1:$BR$30000").AutoFilter Field:=67, Criteria1:=Myvalue3
Application.ScreenUpdating = True
End Sub
Remarks:
Now my sheet named Data will display the extract I want, based on my selection in the pivot. However, if I do not make a selection in, for example, P7 (thus the PivotTable shows (All) in cell P7) then everything is filtered away and there is no data to display.
The reason I want to filter my raw data rather than double-click the pivot to see the detailed data, is because I want to be able to edit the data I select and save the changes afterwards.
Question:
How do I tell my code to leave Column 12 (Myvalue1) unfiltered if the value of Cell P7 is (All)?
Thanks!
I have the following Excel spreadsheet:
In Column C you can see the sales from the products in Column B. In Column A you can find the corresponding brand to each of the products in Column B.
Based on these datas I created the following PivotTable:
In my PivotTable I created a calculated field called sales per day with the following formula:
This gives me exaclty the result I need but as you can see I entered the number of days (in this case 360) as a fixed number into the function of the calculated field.
However, I would prefer to not enter this number as a fixed rate and have it flexible in my PivotTable so the user changes the number in Cell F1 in the database and it automatically applies correctly to the PivotTable.
Do you have any idea how I can solve this issue?
Is there a helper column I could use for it?
Sorry for only having the PivotTable descriptions available in German.
Put this code into the worksheet's private code sheet (right-click, View Code) not a public module code sheet.
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Count > 1 Then Exit Sub
If Target.Address = "$F$1" And CBool(Len(Target.Value2)) Then
On Error GoTo safe_exit
Application.EnableEvents = False
If IsNumeric(Target.Value2) Then
Debug.Print Target.Address
Me.PivotTables("PivotTable1"). _
CalculatedFields("sales per day").StandardFormula = _
"=sales/" & Target.Value2
End If
End If
safe_exit:
Application.EnableEvents = True
End Sub
You may have to adjust some identifying names. Now, whenever you type a new numeric value into F1, the pivot table's calculated 'sales per day' field will have a new formula.
I have a worksheet that contains the names of all managers and their employees, ideally the way this sheet needs to work is that there is a drop down in the top left and when a manager selects their name, all rows that don't have their name against, are hidden, so only their team is shown.
I know auto filtering and having them choose their name would be the easiest way and is a good option to fall back on, but I'm hoping there is a way to do this with VBA or a formula to just hide rows when its not their team when they select their name in the drop down. As i'm trying to create something that's quite slick and looks nice
I did try to do something around having a helper cell to display true and false if the names matched, but came a bit stuck at this point. Tried using the code below, but it doesn't seem to actually be doing anything. Column with TRUE/FALSE is in Col A
Sub TEST()
Dim cell As Range
Application.ScreenUpdating = False
Application.EnableEvents = False
For Each cell In Range("A4:A34")
If cell.Value = "FALSE" Then
cell.EntireRow.Hidden = True
Else
cell.EntireRow.Hidden = False
End If
Next
Application.ScreenUpdating = True
Application.EnableEvents = True
End Sub
Any ideas on how to do this without just using autofilter would be great
Given the following assumptions:
Drop down with Manager name is in cell A1
Column listing manager name for each row is in column A
Data set starts in row 5
Column A is contiguous with no blank spaces
Place the following code into the Worksheet module of the data sheet and change assumptions to fit your data set.
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = "$A$1" and Target.Cells.Count = 1 Then
Application.ScreenUpdating = False
Range("A5:A1000").EntireRow.Hidden = False
Dim mgrList as Range
Set mgrList = Range(Range("A5"),Range("A5").End(xlDown))
Dim mgrCheck as Range
For each mgrCheck in mgrList
mgrCheck.EntireRow.Hidden = mgrCheck <> Target
Next
End If
End Sub
Use an if then else statement with a call that shows/hides the rows that you'd like to show.
If Range("A1").Value = "John Snow" Then
Call Show_John_Snow
Else
If Range("A1").Value = "Daenerys Targaryen" Then
Call Show_Daenerys
Else....
'subroutine
Show_John_Snow
Rows("17:20").EntireRow.Hidden = True 'hide others
Rows("21:53").EntireRow.Hidden = False 'show John Snow
Rows("54:75").EntireRow.Hidden = True 'hide others
I have this data, in which I have Headers at A3:D3, data starting from row 4 to 99.
I tried applying Autofilter, check if this one works for you.
Sub test()
Range("A3:D3").Select
Selection.AutoFilter
ActiveSheet.Range("A3:D99").AutoFilter Field:=2, Criteria1:="0"
ActiveSheet.Range("A3:D99").AutoFilter Field:=2, Criteria1:="1"
End Sub
Here, I selected option named "0" from drop-down filter from Field-2, that is Range A4, and as you told, other cells automatically gets hidden, and the cells corresponding to that criteria only gets visible.
Also I tried with other option "1".
This seems a very difficult or involved way to do this, I have to show students their results without them seeing other students results.
So, one sheet has all the data and on a "front" sheet I call the relevant data for the particular student using index() and match(). Each student has an ID number which is entered, then for confirmation the name is returned then the relevant grades.
I have hidden rows with checkbox macros
Every time I want to insert a new row, the vba code gets messed up and the code assigned to hide rows below will not work
is there a way to dynamically have the rows change the code in the vba
So I don't have to redo all the row values and check boxes that move in the process
[IMG]http://i39.tinypic.com/2akek5z.jpg[/IMG]
Sub CheckBox1_Click()
If Range("B3").Value = True Then
Rows("4:18").EntireRow.Hidden = False
Else
Rows("4:18").EntireRow.Hidden = True
End If
End Sub
Sub CheckBox2_Click()
If Range("B51").Value = True Then
Rows("52:66").EntireRow.Hidden = False
Else
Rows("52:66").EntireRow.Hidden = True
End If
End Sub
I have about 10 subcheckboxes in the code
If I insert or delete a row the code below will not work.
This is because the rows have changed
from the original code that I wrote
Edit
Use 'Named Ranges' instead of hard coding the range. The named range will automatically update when you insert a new row. For example:
I selected rows 9 thru 13 and named them 'RowsABC' as shown here:
I also named my checkbox cell as 'CheckABC' so that it is no longer dependent on what row it's in.
Your code now looks like this:
If Range("CheckABC").Value = True Then
Range("RowsABC").EntireRow.Hidden = False
Else
Range("RowsABC").EntireRow.Hidden = True
End If
Now you can select a row such as row 10 and right click -> insert, and your macro will hide rows 9:14 instead of 9:13 because the named range will update automatically when you insert.