i have a hard time finding the solution for this error, i checked many posts but to no avail, it stays that there is a problem with this line
Set ptable = pCache.CreatePivotTable( _
TableDestination:=DestSheet.Cells(1, 1), _
TableName:="PivotTable1", _
DefaultVersion:=6)
so here is the code
Sub TestPivot()
Dim mySourceData As String
'Declare Variables
Dim SourceSheet As Worksheet
Dim DestSheet As Worksheet
'Declare Variales row and column
Dim FirstRow As Long
Dim LastRow As Long
Dim FirstCol As Long
Dim LastCol As Long
Dim ptable As PivotTable
Dim pCache As PivotCache
'Set/Define Source and Destination Variables
With ThisWorkbook
Set SourceSheet = Worksheets("W")
Set DestSheet = Worksheets("Pivot_W")
End With
'identify first row and first column of source data cell range
FirstRow = 2
FirstCol = 2
'Find last row and last column of source data cell range
'And obtain address of source data cell range
With Sheets("W").Range("A:N")
LastRow = Cells(Rows.Count, "A").End(xlUp).Row
LastCol = Cells(1, Columns.Count).End(xlToLeft).Column
mySourceData = .Range(.Cells(FirstRow, FirstCol), .Cells(LastRow, LastCol)).Address(ReferenceStyle:=xlR1C1)
End With
'Insert Pivot Table
Set pCache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=SourceSheet.Name & "!" & mySourceData, Version:=6)
Set ptable = pCache.CreatePivotTable(TableDestination:=DestSheet.Cells(1, 1), TableName:="PivotTable1", DefaultVersion:=6)
If Not IsEmpty(ptable) Then
MsgBox "non vide"
End If
With DestSheet.PivotTables("PivotTable1").PivotFields("Magasin")
.Orientation = xlRowField
.Position = 1
End With
End Sub
I appreciate your help and thank you for reading my post.
Related
I keep having the same error "13" "type incompatibility" while doing a pivot table.
Sub tracer()
Dim cache As PivotCache
Dim table As PivotTable
Dim prange As range
Dim lastrow As Long
Dim lastcol As Long
lastrow = data.Cells(data.Rows.count, "A").End(xlUp).Row
lastcol = 15
Set prange = data.Cells(1, 1).Resize(lastrow, lastcol)
graphe_clos.Select
Set cache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=prange)
Set table = cache.CreatePivotTable(TableDestination:=graphe_clos.Cells(1, 1), TableName:="Terminator")
End Sub
Thank you for Help
The safer way to assign SourceData to your PivotCache is by using the following line
Set Cache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=pRange.Address(False, False, xlA1, xlExternal))
adding the fourth parameter xlExternal verifies that the range is also pulling the worksheet's name.
See more explanation inside the code's comments.
Modified Code
Sub tracer()
Dim Cache As PivotCache
Dim Table As PivotTable
Dim pRange As Range
Dim LastRow As Long
Dim LastCol As Long
' use With statement to shorten and fully qualify all your nested objects
With Data
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
LastCol = 15
' set the Range of the Pivot's data
Set pRange = .Range(.Cells(1, 1), .Cells(LastRow, LastCol))
' graphe_clos.Select '<-- you don't need to "Select" the sheet in order to create the Pivot-Table
End With
' set the Pivot Cache
Set Cache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=pRange.Address(False, False, xlA1, xlExternal))
' set the Pivot Table
Set Table = Cache.CreatePivotTable(TableDestination:=graphe_clos.Cells(1, 1), TableName:="Terminator")
End Sub
Regarding your latest question, modify:
With ActiveSheet.PivotTables("Terminator").PivotFields("Evt F")
With
With Table.PivotFields("Evt F")
since you already set your PivotTable object to Table.
I'm trying to use VBA to find the Sheet1 column header “Country”, and copy it along with the 20 columns to the right of it, to to Sheet2 column A
I have tried:
Dim lr As Long, lc As Long, Col as Long
With ThisWorkbook.Worksheets("Sheet1")
Col = Application.Match("Country", Sheets("Sheet1").Rows(1), 0)
lr = .Cells(Rows.Count, 1).End(xlUp).Row
lc = .Cells(1, Columns.Count).End(xlToRight).Column
With .Cells (lr, 20).Copy Destination:= Sheets("Sheet2"). Column (“A:A”)
End With
End With
Here's your code, refactored and pointing out the issues in comments
Sub Demo()
Dim lr As Long
'lc not used, left out
Dim Col As Variant 'allow for possibility Country is not found
With ThisWorkbook.Worksheets("Sheet1")
' Use the with block
' Sheets("Sheet1") may or may not be the same sheet as ThisWorkbook.Worksheets("Sheet1")
'Col = Application.Match("Country", Sheets("Sheet1").Rows(1), 0)
Col = Application.Match("Country", .Rows(1), 0)
' Allow for possibility Country is not found
If Not IsError(Col) Then
' Rows.Count refers to the ActiveSheet,
' which may or may not have the same number of rows as ThisWorkbook.Worksheets("Sheet1")
' You are also assuming that Column A has at least the number of rows as your data.
' Is this what you want?
'lr = .Cells(Rows.Count, 1).End(xlUp).Row
lr = .Cells(.Rows.Count, 1).End(xlUp).Row
' Specify the source range, starting at row 1, column containing Country
' then resize to the required size: lr rows, 21 columns
' Specify destination as top left cell, on the fully qualified sheet
.Cells(1, Col).Resize(lr, 21).Copy Destination:=ThisWorkbook.Worksheets("Sheet2").Cells(1, 1)
' Alternative, if you don't need to copy formatting.
'Dim r As Range
'Set r = .Cells(1, Col).Resize(lr, 21)
'ThisWorkbook.Worksheets("Sheet2").Cells(1, 1).Resize(r.Rows.Count, r.Columns.Count).Value _
' = r.Value
End If
End With
End Sub
Find header with text "Country" (I'm assuming your header is in Row 1)
Once found, Copy the "Country" column and 19 columns to right
Paste in Sheet2 A1
Sub ColumnHunt()
Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1")
Dim pr As Range: Set pr = ThisWorkbook.Sheets("Sheet2").Range("A1") 'pr = Paste Range
Dim lr As Long, Found As Range
lr = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
Set Found = ws.Cells(1, 1).EntireRow.Find("Country")
If Not Found Is Nothing Then
ws.Range(ws.Cells(1, Found.Column), ws.Cells(lr, Found.Column + 20)).Copy pr
Else
MsgBox "Country Column Not Found", vbCritical
End If
End Sub
I hope my following code (with some comments) will help
Option Explicit
Private Sub CommandButton1_Click()
' Get the last Row Number of your Data
Dim myLastRow As Integer
myLastRow = Sheet1.Cells(Sheet1.Rows.Count, "A").End(xlUp).Row
' Get the Column Number of your Header Name = "Country"
Dim myHeaderString As String
Dim myHeaderCell As Range
myHeaderString = "Country"
Set myHeaderCell = Sheet1.Rows(1).Find(What:=myHeaderString, LookIn:=xlValues, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
' Be sure that we find that column, send an error message if NOT
If Not myHeaderCell Is Nothing Then
' Get your Source Data Range
Dim myColumnNo As Integer
myColumnNo = myHeaderCell.Column
Dim myRange As Range
Set myRange = Sheet1.Range(Sheet1.Cells(1, myColumnNo), Sheet1.Cells(myLastRow, myColumnNo + 20))
' Copy The Source Data Range
Sheet1.Activate
myRange.Copy
' Past to the Target location
Sheet2.Activate
Sheet2.Cells(1, 1).Select
Sheet2.Paste
Else
MsgBox "No Column Header found"
End If
End Sub
Respected Expert, I am trying to execute below VBA code for Define my data and refresh the Pivot Table but I Am getting defined or object defined error-1004. Please guide me where I am doing mistake on below.
Sub Pivot()
Dim shPivot As Worksheet
Dim shData As Worksheet
Dim lr As Long
Dim lc As Long
Dim rng As Range
Set shPivot = ActiveWorkbook.Sheets("Data")
Set shData = ActiveWorkbook.Sheets("Pivot")
lr = shPivot.Range("A" & Rows.Count).End(xlUp).Row
Set rng = shPivot.Range(Cells(1, 1), Cells(lr, 32))
With shData.PivotTables("PivotTable1").PivotCache
.SourceData = rng.Address(True, True, xlR1C1, True)
.Refresh
End With
End Sub
Try the code below:
Option Explicit
Sub Pivot()
Dim shPivot As Worksheet
Dim shData As Worksheet
Dim PT As PivotTable
Dim PTCache As PivotCache
Dim lr As Long
Dim lc As Long
Dim Rng As Range
Set shPivot = ActiveWorkbook.Sheets("Data")
Set shData = ActiveWorkbook.Sheets("Pivot")
With shPivot
lr = .Range("A" & .Rows.Count).End(xlUp).Row
Set Rng = .Range(.Cells(1, 1), .Cells(lr, 32))
End With
' set the Pivot Cache with the updated Data Source
' Set PTCache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=Rng)
' === Option 2 : set the Pivot Cache with the updated Data Source ===
Set PTCache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=shPivot.Name & "!" & Rng.Address(True, True, xlR1C1, False))
' Set the Pivot Table to existing "PivotTable1" in "Data" sheet
Set PT = shData.PivotTables("PivotTable1")
With PT
.ChangePivotCache PTCache
.RefreshTable
End With
End Sub
I am trying to write a code to create a pivot table (as part of a much larger code) and I just can't get it to detect the source data. Unfortunately, each time the code will run the data will be of a different number of rows, so I want the code to automatically find the last cell with data in it.
I keep getting errors stating that an object is required or a variable is not defined. Despite going to the VBA error guide, I cant find what is wrong.
Can anyone see what the problem here is? Or even if there is a more efficient way to do it?
Sub CreatePivotTable()
Dim sht As Worksheet
Dim pvtCache As PivotCache
Dim pvt As PivotTable
Dim StartPvt As String
Dim SrcData As Range, LRow As Range, LCol As Range
'Determine the data range you want to pivot
Set LRow = Cells(Rows.Count, 1).End(xlUp).Row
Set LCol = Cells(1, Columns.Count).End(xlToLeft).Column
Set SrcData = Worksheets("Raw Data").Range("A1:Cells(LRow,LCol)")
'Create a new worksheet
Sheets.Add.Name = "Pivot Table"
'Where do you want Pivot Table to start?
StartPvt = Worksheets("Occupancy").Range("A15")
'Create Pivot Cache from Source Data
Set pvtCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=SrcData)
'Create Pivot table from Pivot Cache
Set pvt = pvtCache.CreatePivotTable(TableDestination:=StartPvt, TableName:="Occupancy")
'Create the headings and row and column orientation
pvt.PivotFields("Precinct").Orientation = xlPageField
pvt.PivotFields("Number").Orientation.xlDataField.Function = xlCount
pvt.PivotFields("Captured Date").Orientation.xlColumnField.Position = 1
pvt.PivotFields("Captured Session").Orientation.xlColumnField.Position = 2
pvt.PivotFields("Session Location").Orientation.xlRowField.Position = 1
'Turn on Automatic updates/calculations --like screenupdating to speed up code
pvt.ManualUpdate = False
End Sub
Anything within quotes is a string and hence "A1:Cells(LRow,LCol)" becomes a string and doesn't take the address of the cells(LRow,LCol)
Change
Set SrcData = Worksheets("Raw Data").Range("A1:Cells(LRow,LCol)")
to
LastCol = Split(Cells(, LCol).Address, "$")(1)
Set SrcData = Worksheets("Raw Data").Range("A1:" & LastCol & LRow)
or to this
Set SrcData = Worksheets("Raw Data").Range("A1:" & Cells(LRow,LCol).Address(False, False))
Also change
Dim LRow As Range, LCol As Range
Set LRow = Cells(Rows.Count, 1).End(xlUp).Row
Set LCol = Cells(1, Columns.Count).End(xlToLeft).Column
to
Dim LRow As Long, LCol As Long
LRow = Cells(Rows.Count, 1).End(xlUp).Row
LCol = Cells(1, Columns.Count).End(xlToLeft).Column
Use a table to store the data and give it a name. Then set the pivot source to the table name
I am trying to add a pivot table to the same worksheet I am on (the sheet is called holders (corp)) but am having trouble with that.
Sub PivotTable()
Sheets("Sheet2").Select
Dim sht As Worksheet
Dim pvtCache As PivotCache
Dim pvt As PivotTable
Dim pf As PivotField
Dim StartPvt As String
Dim SrcData As String
Dim LastRow As Long
LastRow = Cells(Rows.Count, "A").End(xlUp).row
'Determine the data range you want to pivot
SrcData = ActiveSheet.Name & "!" & Range(Cells(1, "A"), Cells(LastRow,"E")).Address(ReferenceStyle:=xlR1C1)
'Create a new worksheet
Set sht = Sheets("HOLDERS (CORP)")
'Where do you want Pivot Table to start?
StartPvt = sht.Name & "!" & sht.Range("A1").Address(ReferenceStyle:=xlR1C1)
'Create Pivot Cache from Source Data
Set pvtCache = ActiveWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=SrcData)
'Create Pivot table from Pivot Cache
Set pvt = pvtCache.CreatePivotTable( _
TableDestination:=StartPvt, _
TableName:="HolderssPivotTable")
End Sub
I get a debug issue related to the call procedure at the very last 3 lines of code but am not sure why. Help would be much appreciated!
Excel VBA cannot accept R1C1 cell addresses in Range objects.
Change
StartPvt = sht.Name & "!" & sht.Range("A1").Address(ReferenceStyle:=xlR1C1)
To
StartPvt = sht.Range("A1").Address
Then change
Set pvt = pvtCache.CreatePivotTable( _
TableDestination:=StartPvt, _
TableName:="HolderssPivotTable")
End Sub
To
Set pvt = pvtCache.CreatePivotTable(TableDestination:=sht.Range(StartPvt), _
TableName:="HolderssPivotTable")
Update - Full refactored code to ensure pivot table ends up on Holders (CORP) sheet.
Sub PivotTable()
Dim sht2 As Worksheet
Set sht2 = Sheets("Sheet2")
With sh2
Dim LastRow As Long
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
'Determine the data range you want to pivot
Dim SrcData As String
SrcData = .Name & "!" & .Range(.Cells(1, "A"), .Cells(LastRow, "E")).Address
End With
Dim sht As Worksheet
'Create a new worksheet
Set sht = Sheets("HOLDERS (CORP)")
'Where do you want Pivot Table to start?
Dim StartPvt As String
StartPvt = sht.Range("A1").Address
'Create Pivot Cache from Source Data
Dim pvtCache As PivotCache
Set pvtCache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=SrcData)
'Create Pivot table from Pivot Cache
Dim pvt As PivotTable
Set pvt = pvtCache.CreatePivotTable(TableDestination:=sht.Range(StartPvt), TableName:="HolderssPivotTable")
End Sub