I'm trying to figure out why my Pivot table filtering is so very slow, using VBA. The table itself doesn't have too many rows - about 5000 in total. But this slice of code takes about 30 seconds to make the update, and it makes Excel appear to be frozen. I'm using an Array to pass in two values to the filter that I am using. In this case, there are two "People" that I want to select in this filter. What am I missing?
'
Set PT = ActiveSheet.PivotTables("PivotTable1")
Dim i As Integer
i = 0
For Each PTItm In PT.PivotFields("Person").PivotItems
i = i + 1
If Not IsError(Application.Match(PTItm.Caption, myArray, 0)) Then
PTItm.Visible = True
Else
PTItm.Visible = False
End If
Next PTItm
As additional information, I also tried to start by setting Visible = False on all of the items (except for the last Item, since you have to leave at least one Item visible), and then just setting the Visible = True for the Items that I want. But the problem is that just getting through all of the Items and setting to False (snip below) takes the same ~ 30 seconds.
With PT
For jj = 1 To .PivotFields("Person").PivotItems.Count - 1
.PivotFields("Person").PivotItems(jj).Visible = False
Next
End With
Related
I am currently creating a competence matrix which should have some functionality installed that it only shows the relevant columns for a certain department. Within a department a group of people is working and performing a X number of tasks where they are skilled for. The sum of tasks for all departments is so high the the overview will be lost if each department has to look for data in all columns.
Therefore, I am looking for a way to only display the columns for a department where one of the columns at least contains a number higher than 0 (which is equal to untrained/not in scope for that department). By that the columns should only remain that are applicable to that department.
See below screenshot for an impression of the competence matrix:
Example code:
Department,Expedition,WAC,Unpacker,Stagnation,Runner,Runner MLX
D2S,5,5,3,5,0,5
D2S,5,2,0,5,0,5
S2F,0,0,4,5,0,0
S2F,0,0,1,0,0,5
Above code more or less does the trick already, but this is not dynamic. As soon as a column is inserted, the hidden columns are not correct anymore. Also, it should contain the functionality where people will be crosstrained and thus more columns need to be visible as soon as people are trained for a process that currently does not belong to a certain department. Below code does not suffice this option:
Public Sub Hide_Department_Columns(dataSheet As Worksheet)
Dim Department As String
With dataSheet
If .AutoFilterMode Then
Department = .AutoFilter.Range.Offset(1, 0).SpecialCells(xlCellTypeVisible)(1, 5).Value '5 is column E
Application.ScreenUpdating = False
Select Case Department
Case "D2S"
.Columns("A:Z").Hidden = False 'unhide all columns
.Range("AA:AM").EntireColumn.Hidden = True
Case "S2F"
.Columns("A:Z").Hidden = False
.Range("AI:AI,AN:AZ").EntireColumn.Hidden = True
Case "S2F - 5 Shift"
.Columns("A:Z").Hidden = False
.Range("AG:AG,AN:AQ,AV:AX,BA:BJ").EntireColumn.Hidden = True
Case "F2S"
.Columns("A:Z").Hidden = False
.Range("AS:AS,BK:BT").EntireColumn.Hidden = True
Case "EHV1"
.Columns("A:Z").Hidden = False
.Range("AB:AB,BM:BM,BU:CC").EntireColumn.Hidden = True
Case "Best2"
.Columns("A:Z").Hidden = False
.Range("AB:AB,BM:BM,BU:BW,BY:CB").EntireColumn.Hidden = True
Case Else
.Columns("A:Z").Hidden = False
End Select
Application.ScreenUpdating = True
End If
End With
End Sub
Can someone help me in how I would build in this functionality. I am thinking of something like: If column F value is filtered a certain department (E.G.) and if any value within range AB13:CD:2000 is higher than 0 show that column.
I tried the code used, but it does not suffice the dynamic function.
I have a problem with SAP VA02 where I want to identify the row line in which a specific label is. In this case the label/text is "Cust. expected price".
I am trying to change the data next to this row, problem is that it is not always the same row, sometimes it is 16, 18, etc.
I am trying to find a way to loop through each row in column 2 in the structure, read the text, and find which row the label is in, then use the row as a variable to paste the price in the correct cell. I have pasted some functioning code below.
What I am doing is inputting the correct price here:
session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_ITEM/tabpT\05/ssubSUBSCREEN_BODY:SAPLV69A:6201/tblSAPLV69ATCTRL_KONDITIONEN/txtKOMV-KBETR[3,16]").Text = Price
My main question is how to read what text is in each cell for example session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_ITEM/tabpT\05/ssubSUBSCREEN_BODY:SAPLV69A:6201/tblSAPLV69ATCTRL_KONDITIONEN/txtKOMV-KBETR[2,16]")
I can probably figure out the rest from there. I haven't been able to find much regarding this specific structure, any input is appreciated. I will also post a screenshot of the page for reference. Thank you!
Sub OrderRelease()
Dim Order As String
Dim RowCount As Integer
Dim Item As Integer
Dim sh As Worksheet
Dim rw As Range
Dim Sroll As Integer
Dim Price As Double
On Error Resume Next
RowCount = 0
Set sh = ActiveSheet
For Each rw In sh.Rows
If sh.Cells(rw.Row, 6).Value = "" Then
Exit For
End If
RowCount = RowCount + 1
Next rw
If Not IsObject(SAPGuiApp) Then
Set SapGuiAuto = GetObject("SAPGUI")
Set SAPGuiApp = SapGuiAuto.GetScriptingEngine
End If
If Not IsObject(Connection) Then
Set Connection = SAPGuiApp.Children(0)
End If
If Not IsObject(SAP_session) Then
Set session = Connection.Children(0)
End If
If IsObject(WScript) Then
WScript.ConnectObject SAP_session, "on"
WScript.ConnectObject SAPGuiApp, "on"
End If
session.findById("wnd[0]").maximize
session.findById("wnd[0]/tbar[0]/okcd").Text = "/nva02"
session.findById("wnd[0]").sendVKey 0
For i = 2 To RowCount
Order = Cells(i, "F")
session.findById("wnd[0]/usr/ctxtVBAK-VBELN").Text = Order
session.findById("wnd[0]/usr/ctxtVBAK-VBELN").caretPosition = 9
session.findById("wnd[0]").sendVKey 0
session.findById("wnd[1]/tbar[0]/btn[0]").press
Continue:
Item = Cells(i, "G") / 10 - 1
Scroll = Item - 1
Price = Cells(i, "H")
Set sub = session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_OVERVIEW/tabpT\02/ssubSU" _
& "BSCREEN_BODY:SAPMV45A:4401/subSUBSCREEN_TC:SAPMV45A:4900")
Set tbl = sub.findById("tblSAPMV45ATCTRL_U_ERF_AUFTRAG")
tbl.verticalScrollbar.Position = Scroll
tbl.getAbsoluteRow(Item).Selected = True
tbl.findById("txtVBAP-POSNR[0,8]").SetFocus
tbl.findById("txtVBAP-POSNR[0,8]").caretPosition = 4
sub.findById("subSUBSCREEN_BUTTONS:SAPMV45A:4050/btnBT_PKON").press
Set tbl2 = session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_ITEM/tabpT\05/ssubSU" _
& "BSCREEN_BODY:SAPLV69A:6201/tblSAPLV69ATCTRL_KONDITIONEN")
tbl2.verticalScrollbar.Position = 8
'The below line is what I need to find. In this case, Cust. expected price would be 2,16,
'but I have not found a way to actually read the text in that cell.
tbl2.findById("txtKOMV-KBETR[3,16]").Text = Price
tbl2.findById("txtKOMV-KBETR[3,16]").SetFocus
tbl2.findById("txtKOMV-KBETR[3,16]").caretPosition = 16
session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_ITEM/tabpT\11").Select
session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_ITEM/tabpT\11/ssubSU" _
& "BSCREEN_BODY:SAPMV45A:4456/cmbVBAP-ABGRU").Key = " "
session.findById("wnd[0]/tbar[0]/btn[3]").press
session.findById("wnd[0]/usr/btnBUT2").press
session.findById("wnd[1]/tbar[0]/btn[0]").press
session.findById("wnd[0]").sendVKey 0
If Cells(i, "F") = Cells(i + 1, "F") Then
i = i + 1
GoTo Continue
End If
session.findById("wnd[0]").sendVKey 11
session.findById("wnd[1]/tbar[0]/btn[0]").press
session.findById("wnd[1]/usr/btnSPOP-VAROPTION1").press
Next i
End Sub
Here is how to refer to a value of a cell in a given row and a given column, which are both provided in variables:
row = 0
column = 1
cellText = session.findById(".../tblXXXXX/columnFieldName[" & column & "," & row & "]").Text
Another solution is to use the method GetCell on the Table Control object:
cellText = session.findById(".../tblXXXXX").GetCell(row,column).Text
NB: notice that row and column arguments are switched.
To know what values to use for ".../tblXXXXX/columnFieldName[...], the easiest way is to record a script, by simply moving the cursor to the desired column. The generated script will return something like that (test with the demo program DEMO_DYNPRO_TABCONT_LOOPFLIGHTS):
session.findById("wnd[0]/usr/tblDEMO_DYNPRO_TABCONT_LOOPFLIGHTS/ctxtDEMO_CONN-CITYFROM[2,1]").setFocus
session.findById("wnd[0]/usr/tblDEMO_DYNPRO_TABCONT_LOOPFLIGHTS/ctxtDEMO_CONN-CITYFROM[2,1]").caretPosition = 1
The row number corresponds to the order among the visible rows, starting from 0 (0 = first visible row). The last visible row has the number equals to the Table Control property VisibleRowCount minus 1. The rows which are not visible (above and below) can be accessed by making your script scroll vertically, for more information about scrolling programatically see below chapter.
The column number is based on the order of columns shown in the Table Control, whatever the columns are immediately visible or visible after horizontal scrolling. The script doesn't need to perform horizontal scrolling to read the values of non-visible columns. 0 is the leftmost column, and the rightmost column has the number equals to the two properties of the Table Control Columns.Count minus 1.
The list of columns and their order may vary according to the active Table Control configuration. You may wish to determine the column number based on the column name at run time, for that see below chapter.
There may be other columns proposed via the Table Control administrator function, with the "hidden" checkbox selected. SAP GUI Scripting completely ignores these columns. If you need to work with them, you must call the table control method ConfigureLayout to display the administrator screen, and then you can work with the settings as you do with any other screen.
Scrolling the rows
For a Table Control, SAP GUI Scripting knows only the data in the lines which are currently visible on the screen, because for performance reason the backend ABAP program sends only these lines to the frontend. SAP GUI Scripting can't know the values from the invisible lines. It's required that the script scrolls vertically to obtain the other rows. Attention, scrolling means the reloading of the whole screen, so the screen elements need to be re-instantiated. The following example scrolls the whole list to display all the values in the first column (use of the demo program DEMO_DYNPRO_TABCONT_LOOPFLIGHTS):
Set tbl = session.findById("wnd[0]/usr/tblDEMO_DYNPRO_TABCONT_LOOPFLIGHTS")
' Make the first row visible (show the top of the list) -> that calls the back-end system and screen is reloaded.
' ATTENTION: when the back-end is called, to continue working with screen elements, they must be re-instantiated.
tbl.VerticalScrollbar.Position = 0
TextsOfAllCellsInColumnZero = ""
Do While True
' Re-instantiate the Table Control element (mandatory each time the back-end is called)
Set tbl = session.findById("wnd[0]/usr/tblDEMO_DYNPRO_TABCONT_LOOPFLIGHTS")
visibleRow = 0
currentScrollbarPosition = tbl.VerticalScrollbar.Position
While visibleRow < tbl.VisibleRowCount And currentScrollbarPosition <= tbl.VerticalScrollbar.Maximum
TextsOfAllCellsInColumnZero = TextsOfAllCellsInColumnZero & tbl.GetCell(visibleRow,0).Text & Chr(10)
visibleRow = visibleRow + 1
currentScrollbarPosition = currentScrollbarPosition + 1
Wend
If currentScrollbarPosition > tbl.VerticalScrollbar.Maximum Then
Exit Do
End If
tbl.VerticalScrollbar.Position = currentScrollbarPosition
Loop
MsgBox TextsOfAllCellsInColumnZero
Note that this example is suitable to a small number of pages. In many other situations, there are many more pages, for an action like searching a line containing a given value, it would be much more performing to click an existing button to perform a back-end search of this value. The right page would be immediately be displayed.
Determine the column number from the column name at run time
As explained above, the column number may vary depending on the order of columns and on hidden columns. If they vary in an undetermined way at run time, the following code allows to determine the column number based on the column name (note that the lower case prefix of the field name is to be removed, like "ctxt" in "ctxtDEMO_CONN-CITYFROM"), but it works only if there's at least 1 row (no solution found if it's needed when the Table Control is empty):
Set tbl = session.findById("wnd[0]/usr/tblDEMO_DYNPRO_TABCONT_LOOPFLIGHTS")
column = GetColumnNumberByName(tbl,"DEMO_CONN-CITYFROM")
msgbox tbl.GetCell(row,column).text
Function GetColumnNumberByName( TableControl, ColumnName )
If TableControl.Rows.Count > 0 Then
For i = 0 To TableControl.Columns.Count - 1
If TableControl.Columns(i)(0).Name = ColumnName Then
GetColumnNumberByName = i
Exit Function
End If
Next
End If
GetColumnNumberByName = -1
End Function
Appendix
For more information, please refer to the documentation of the "GuiTableControl Object" in the SAP Library.
NB: if you look at other questions, be aware that a Table Control (GuiTableControl) is completely unrelated to a Grid View (GuiGridView), so don't be confused.
I am trying to find a way to use Excel 2013 VBA to only select the Top 5 items in a pivot table. I have tried the following lines of code in an attempt to show only the Top 5 items:
Dim c
dim i as long
Worksheets("sheet1").PivotTables(1).PivotFields ("field1")
ActiveSheet.PivotTables(1).PivotFields("field1").CurrentPage = "(All)"
With ActiveSheet.PivotTables(1).PivotFields("field1")
c = 5
For i = .PivotItems.Count To 1 Step -1
If (c > 0) Then
.PivotItems(i).Visible = True
Else
.PivotItems(i).Visible = False
End If
c = c - 1
Next
End With
This is the code that the macro recorder gives me and does not work:
ActiveSheet.PivotTables("PivotTable5").PivotFilters. _
.PivotFields("field1") Add2 Type:=xlTopCount, _ DataField:=ActiveSheet.PivotTables("PivotTable5"). _
PivotFields("fied1"), Value1:=5
The code below works fine if there are no value ties for any of the values that are not in the Top 5 list. With our data set we are always going to ties in our Top 5 list.
With Workbooks(cFileName).Worksheets("sheet1")
.PivotTables(1).PivotFields("Field1").PivotFilters.Add2
xlTopCount, .PivotTables(1).PivotFields("Field1"), 5
End With
EDIT:
The pivot table list will show some items as being checked, but no data is associated with those values. The charts which are based on these pivot tables are blank and the following code selects only the bottom 5 values in the field as it was intended to do in it's original post.
With workbook.Worksheets("sheet1").PivotTables("PivotTable2").PivotFields
("Count of Description")
For Each WS In ActiveWorkbook.Worksheets
For Each pvt In WS.PivotTables
c = 5
For i = .PivotItems.Count To 1 Step -1
If (c > 0) Then
.PivotItems(i).Visible = True
Else
.PivotItems(i).Visible = False
End If
c = c - 1
Next
Next
Next
End With
I finally figured this one out. The best way to do it just in case anyone else is wondering, is to record a macro while you:
Select the cell in which you want to start seeing data. In my case it was "B10". This will be different for everyone else depending on where your pivot table data is.
Press the SHIFT + END + DOWN ARROW Keys to go down to the bottom of the used range.
Select all the rows to hide.
Right Click on the values to hide.
Select "Filter" from the list.
Click on "Hide selected items".
Below is the code that I will refer to in the future.
Application.Goto reference:=Workbooks("File").Sheets("Sheet1").Range("B10")
If IsEmpty(Range("B11").value) = False Then
Range("B10").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Delete
Else
End If
I am trying to load a listbox with items with two columns, check each entry against a spreadsheet, and select the row if that entry is found.
The result is loading a customer list, identifying and selecting the items already on a mailing list, allowing the user to edit the selection and updating the spreadsheet with the updated selection.
I tried to do the check within the loading of the listbox, but since I was tripping with errors I separated it out to make things clearer, the error occurs in the code below on the line CRM_Edit_Groups.ListBox1(j).Selected = True
With Rows(1)
Set c = .Find(What:=showgroup, LookIn:=xlValues, LookAt:=xlWhole)
End With
For i = 0 To wk.Sheets("temp").UsedRange.Rows.count + 1
code = wk.Sheets("temp").Range("a" & mycount)
company_name = wk.Sheets("temp").Range("b" & mycount)
CRM_Edit_Groups.ListBox1.ColumnCount = 2
CRM_Edit_Groups.ListBox1.ColumnWidths = "40;80"
CRM_Edit_Groups.ListBox1.AddItem
CRM_Edit_Groups.ListBox1.list(i, 0) = code
CRM_Edit_Groups.ListBox1.list(i, 1) = company_name
mycount = mycount + 1
Next
For j = 0 To Me.ListBox1.ListCount - 1
check = Me.ListBox1.list(j, 0)
With Columns(c.Column)
Set d = .Find(What:=check, MatchCase:=False)
End With
If Not d Is Nothing Then CRM_Edit_Groups.ListBox1(j).Selected = True
If Not d Is Nothing Then Set d = Nothing
Next
I've included the code for loading the listbox, as well as the loop to check each one against the spreadsheet, I've tried many combinations including:
CRM_Edit_Groups.ListBox1(j,0).Selected = True
CRM_Edit_Groups.ListBox1(j,1).Selected = True
CRM_Edit_Groups.ListBox1(j.row).Selected = True
...but all result in "Run-time error '424': Object required", I know I am not managing to work with the row here but searching the site and google I just find pages of information on how to read the selected items from a listbox and not much on how to select during initialization.
You should use
CRM_Edit_Groups.ListBox1.Selected(j) = True
Also, make sure that your list allows multiple selection. Select your listbox in userform window and go to object properties. There find property MultiSelect and chose option 1.
I have working code which selects single items from a slicer, however it doesn't work for multiple items.
The selection is set up by reading which cells in a range are in bold, and populating an array of strings, STP(46), populating up until STP(k). This works fine.
Then the code is supposed to deselect all items in the slicer which aren't in STP, and select those which are. This works for one selection but not for multiple selections - it erroneously selects all items up until the last item to be selected.
With ActiveWorkbook.SlicerCaches("Slicer_STP_Name")
For i = 1 To .SlicerItems.Count
For j = 1 To k
If .SlicerItems(i).Selected And .SlicerItems(i).Caption <> STP(j) Then .SlicerItems(i).Selected = False
Next j
Next i
For i = 1 To .SlicerItems.Count
For j = 1 To k
If .SlicerItems(i).Caption = STP(j) Then .SlicerItems(i).Selected = True: Exit For
Next j
Next i
End with
So instead of selecting, say, the 2nd and 4th item in the slicer, it selects the 1st, 2nd, 3rd, 4th, and deselects the rest.
I need to use a looped technique like this because I need to be able to use this code with multiple slicers with different cache names but the same list of items.
I've looked everywhere, and the code above is even from a solution from another question on here. Any help greatly appreciated!
You can use a dictionary to make the process a little more smooth
With ActiveWorkbook.SlicerCaches("Slicer_test_id")
Dim i
For i = 1 To .SlicerItems.Count
If .SlicerItems(i).Selected And Not stp.Exists(.SlicerItems(i).Caption) Then
.SlicerItems(i).Selected = False
End If
Next i
For i = 1 To .SlicerItems.Count
If stp.Exists(.SlicerItems(i).Caption) Then
.SlicerItems(i).Selected = True
End If
Next i
End With
I'm not totally clear on why you need the first loop. I'm reading "Then the code is supposed to deselect all items in the slicer which aren't in STP, and select those which are." as "select only those otems in STP and deselect all others" which this reduced code will do:
With ActiveWorkbook.SlicerCaches("Slicer_test_id")
Dim i
For i = 1 To .SlicerItems.Count
.SlicerItems(i).Selected = stp.Exists(.SlicerItems(i).Caption)
Next i
End With
populating the Dictionary is super easy
Dim stp As New Dictionary
stp.Add "73148", "73148"
stp.Add "73150", "73150"
stp.Add "73159", "73159"
You need to reference the Microsoft Scripting Runtime
note that if you don't see Microsoft Scripting Runtime in the list you can Browse to C:\Windows\SysWOW64\scrrun.dll