I need assistance with selecting a Pivot table range to copy into another spreadsheet. What I need to do is copy all the rows and columns for a specific "Project WBS" value that will be searched on.
In my code below I tried using xlDataAndLabel but it only gives me the Project WBS and Pivot Items I need. It leaves out the "Description", "Employee", and "Activity Type" columns. I can't use .EntireRow.Copy because when I go to the other workbook to paste I get an error saying the size is too great.
Your help is greatly appreciated.
Max
Sub getPivotData()
Dim PvtTbl As PivotTable
Set PvtTbl = Worksheets("Aug 18 Report").PivotTables("PivotTable1")
Worksheets("Aug 18 Report").Activate
Application.PivotTableSelection = True
PvtTbl.PivotSelect "GS136.548", xlDataAndLabel
Selection.Interior.Color = vbYellow
End Sub
You could try resizing the target label range to the number of columns in the pivottable
e.g.
Option Explicit
Public Sub test()
Dim pvt As PivotTable, rng As Range
Set pvt = ActiveSheet.PivotTables(1)
With pvt.PivotFields("Project WBS").PivotItems("A").LabelRange
Set rng = Worksheets(pvt.Parent.Name).Range(.Resize(.Rows.Count, pvt.TableRange1.Columns.Count).Address)
Debug.Print rng.Address
End With
End Sub
In the following the highlighted area is the address returned by the print statement
Here is an example of referencing the pivot if it is in a different (open) workbook:
Option Explicit
Public Sub test()
Dim pvt As PivotTable, rng As Range
Dim wb As Workbook, ws As Worksheet
Set wb = Workbooks("Book3.xlsb")
Set ws = wb.Worksheets("Sheet1")
Set pvt = ws.PivotTables(1)
With pvt.PivotFields("Project WBS").PivotItems("A").LabelRange
Set rng = ws.Range(.Resize(.Rows.Count, pvt.TableRange1.Columns.Count).Address)
Debug.Print rng.Address
End With
End Sub
Related
I have a budget template with tables for each budget category. I have buttons for users to add rows to each budget category with the rows in each category being set as a table so that my total functions work no matter how many rows are added where. But Id like users to also be able to delete rows like if they add too many or if roles change during the time the budget is changed, etc. I don't want users to be able to delete rows such as headers or totals. Protecting the rows doesn't work since the row number can change at any time with new rows being added at any time. The delete selected row code is below as well as my add a row code for the first category which is full time employee salary.
delete selected row - not good since can delete important rows
Sub DeleteSelectedRow()
Rows(ActiveCell.Row).Delete
End Sub
add row to category - good since adds rows to table to keep formulas working
Sub AddConsultant()
Dim ws As Worksheet
Dim tbl As ListObject
Set ws = ActiveSheet
Set tbl = ws.ListObjects("Consultants")
tbl.ListRows.Add
End Sub
Try this:
Sub AddConsultant()
Dim ws As Worksheet
Dim tbl As ListObject
Set ws = ActiveSheet
Set tbl = ws.ListObjects("Consultants")
tbl.ListRows.Add
End Sub
Sub DeleteSelectedRow()
Dim ws As Worksheet
Dim tbl As Range
Set ws = ActiveSheet
Set tbl = ws.ListObjects("Consultants").Range
If InRange(ActiveCell, tbl) Then
Rows(ActiveCell.Row).Delete
Else
MsgBox ("Cannot Delete")
End If
End Sub
Function InRange(Range1 As Range, Range2 As Range) As Boolean
' returns True if Range1 is within Range2
Dim InterSectRange As Range
Set InterSectRange = Application.Intersect(Range1, Range2)
InRange = Not InterSectRange Is Nothing
Set InterSectRange = Nothing
End Function
You can check whether the selection (or part of the selection) range is inside the table of interest.
For example:
Sub AddConsultant()
AddRow "Consultants"
End Sub
Sub RemoveConsultant()
RemoveSelectedRow "Consultants"
End Sub
Sub AddSite()
AddRow "Sites"
End Sub
Sub RemoveSite()
RemoveSelectedRow "Sites"
End Sub
'methods to add/remove rows from the specified table
Sub AddRow(tableName As String)
ActiveSheet.ListObjects(tableName).ListRows.Add
End Sub
Sub RemoveSelectedRow(tableName As String)
Dim rng As Range, ok As Boolean
If TypeName(Selection) = "Range" Then 'is a range selected?
'is the range in the required table?
Set rng = Application.Intersect( _
ActiveSheet.ListObjects(tableName).DataBodyRange, Selection)
If Not rng Is Nothing Then
rng.EntireRow.Delete
ok = True
End If
End If
'didn't delete anything?
If Not ok Then MsgBox "First select one or more rows in " & _
tableName & " table"
End Sub
In my excel file I have a worksheet for every person. This worksheet is copied according a template sheet after entering data.
Now for the next part I would like to add data to a specific range on the sheet of that person.
Let's start with a simple date stamp to Range E4:E53 for the specified sheet. I'm using a combobox so you can select someone from the list and this is where i'm struggling;
After selecting someone from the list, my code does not write down the data.
As shown in the picture, the Worksheet is set to nothing. How do I set the worksheet according to the selected person from the combobox?
Public Sub CommandButton1_Click()
Dim lRow As String
Dim Rng As Range
Dim Rng2 As Range
Dim ws As Worksheet
Set ws = ComboBox1.List(I, 0)
Set Rng = Range("C4, C53")
Set Rng2 = Range("E4, Q53")
lRow = ws.Cells(Rows.Count, 1).End(xlUp).Row
With ws
Rng.Cells.lRow.Value = Format(Time, "DD:MM:YYYY:HH:MM")
End With
End sub
I assume that your list contains names of worksheets for each person, like {"Monica", "Adam"...}, right?
The problem in your case is that you try to use string value from ComboBox1 to define worksheet which is an object in worksheets collection.
You should get string value (name) of worksheet and then use it to set your ws object.
Here is simple code snippet, hope it is what you wanted to achieve :)
Private Sub ComboBox1_click()
Dim ws As Worksheet
'Define worksheet from worksheets collection
Set ws = worksheets(ComboBox1.Value)
ws.Range("A5").Value = "Hello!"
End Sub
Private Sub UserForm_Initialize()
Dim ws As Worksheet
'Make list of all worksheets
For Each ws In worksheets
ComboBox1.AddItem ws.Name
Next ws
End Sub
I was trying to convert my data to a table to so that the pivot table will update when new data is added, i tried to use a code i found online and updated it with my file but there seem to be some error.
Private Sub CommandButton1_Click()
Dim ws As Worksheet
Dim wscopy As Worksheet
Dim wspaste As Worksheet
Dim src As Range
Set wsfilter = Workbooks("bdncasemacro.xlsm").Worksheets("Filter")
Set src = Range("B5").CurrentRegion
Set ws = wsfilter
wsfilter.ListObjects.Add(SourceType:=xlSrcRange, Source:=src, _
xlListObjectHasHeaders:=xlYes, tablestyleName:="TableStyleMedium28").Name = "Filter"
'update pivot table
Workbooks("bdncasemacro.xlsm").RefreshAll
MsgBox ("DONE!")
End Sub
i got the error "1004" enter image description here
the error occurs from the debug from the lines
wsfilter.ListObjects.Add(SourceType:=xlSrcRange, Source:=src, _
xlListObjectHasHeaders:=xlYes, tablestyleName:="TableStyleMedium28").Name = "Filter"
I have a problem which is probably very easy for you to help me solve.
I have two tables: Table1 and Table2. Both tables are in the same worksheet called "Budget".
I want to add a command button / a plus button, that enables a user to add a new row at the bottom of each table.
However, after trying this via the macro record function, I recognized that at some point, the new rows of Table2 are added somewhere in the middle, after having added several new rows to Table1.
Can someone please provide me with a code, that solves this issue and sort of auto-adjusts?
I have never in my life coded something.
Thank you in advance for your help!
Code from recorder:
Sub NEWROW()
'
' NEWROW Makro
'
'
Range("B12:C12").Select
Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
End Sub
Try this code
Option Explicit
Sub AddRows()
Dim wks As Worksheet
Dim tbl1 As ListObject
Dim tbl2 As ListObject
Set wks = ActiveSheet
Set tbl1 = wks.ListObjects("Table1")
Set tbl2 = wks.ListObjects("Table2")
tbl1.ListRows.Add
tbl2.ListRows.Add
End Sub
Table object is explained here
Update Ok, for an absolute beginner this might be the easiest way to do it.
Sub AddRowTbl1()
Dim wks As Worksheet
Dim tbl As ListObject
Set wks = ActiveSheet
Set tbl = wks.ListObjects("Table1")
tbl.ListRows.Add
End Sub
Sub AddRowTbl2()
Dim wks As Worksheet
Dim tbl As ListObject
Set wks = ActiveSheet
Set tbl = wks.ListObjects("Table2")
tbl.ListRows.Add
End Sub
PS A more advanced user would use a function
Function tblAddRow(tblname As String, wks As Worksheet)
Dim tbl As ListObject
On Error GoTo EH
Set tbl = wks.ListObjects(tblname)
tbl.ListRows.Add
EH:
End Function
Sub Test_tblAdd()
tblAddRow "Table1", ActiveSheet
End Sub
I don't know where I am going wrong but it not working neither giving any error. I am trying to Update my Pivot table with cell values that should filter the given date ranges in cell G3 & G4. But unfortunately not updating the table.
Below is the VBA I am using.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
'This line stops the worksheet updating on every change, it only updates when cell
'G3 or G4 is touched
If Intersect(Target, Range("G3:G4")) Is Nothing Then Exit Sub
'Set the Variables to be used
Dim pt As PivotTable
Dim Field As PivotField
Dim EDate As String
Dim SDate As String
'Here you amend to suit your data
Set pt = Worksheets("Report").PivotTables("PivotTable1")
Set Field = pt.PivotFields("Date")
SDate = Worksheets("Report").Range("G3").Value
EDate = Worksheets("Report").Range("G4").Value
'This updates and refreshes the PIVOT table
With pt
Field.ClearAllFilters
Field.PivotFilters.Add Type:=xlDateBetween, Value1:=SDate, Value2:=EDate
pt.RefreshTable
End Sub
I was able to resolve it myself. Posting the answer below, might be of someone's help.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
'This line stops the worksheet updating on every change, it only updates when cell
'G3 or G4 is touched
If Intersect(Target, Range("G3:G4")) Is Nothing Then Exit Sub
'Set the Variables to be used
Dim pt As PivotTable
Dim Field As PivotField
Dim EDate As String
Dim SDate As String
'Here you amend to suit your data
Set pt = Worksheets("Report").PivotTables("PivotTable1")
Set Field = pt.PivotFields("Date")
SDate = Worksheets("Report").Range("G3").Value
EDate = Worksheets("Report").Range("G4").Value
'This updates and refreshes the PIVOT table
With pt
Field.ClearAllFilters
Field.PivotFilters.Add Type:=xlDateBetween, Value1:=SDate, Value2:=EDate
pt.RefreshTable
End With
End Sub