Pivotcache create runtime error mismatch - vba

I have been trying to create a PivotTable using VBA, but it keeps giving me Pan error message in the PivotCache section.
I have three worksheets on a workbook and I intend to use the table in worksheet 1 to create a pivot table and chart on worksheet 3. But I keep getting an error message.
Here is my vba code:
Dim ws As Worksheet
Dim pc As PivotCaches
Dim pt As PivotTable
Dim Rng As Range
Dim wb As Workbook
Set ws = Worksheets("Sheet3")
Set Rng = Worksheets("Sheet3").Range("A58")
Set pc = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:="Table1", Version:=xlPivotTableVersion14)
Set pt = pc.CreatePivotTable(TableDestination _
:=Range("A58"), TableName:="PivotTable5", DefaultVersion:= _
xlPivotTableVersion14)
ActiveWorkbook.ShowPivotTableFieldList = True
End Sub
Pivot-Table Data screen-shot

Try the code below, explanation inside the code comments:
Option Explicit
Sub PivotTablefromTable()
Dim wb As Workbook
Dim ws As Worksheet
Dim PTbl As PivotTable
Dim PCache As PivotCache
Dim WorkTbl As ListObject
Dim PTblRng As Range
Dim Rng As Range
Set ws = Worksheets("Sheet3")
Set Rng = ws.Range("A58")
Set WorkTbl = Worksheets("work").ListObjects("Table1") ' <-- set a variable to the "Table1" in sheet "work"
Set PTblRng = WorkTbl.Range '<-- get the range from "Table1"
' set the Pivot Cache
Set PCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PTblRng)
' Set the Pivot Table (already created in previous macro run)
On Error Resume Next
Set PTbl = ws.PivotTables("PivotTable5")
On Error GoTo 0
If PTbl Is Nothing Then ' <-- pivot table still doesn't exist >> need to create it
' create a new Pivot Table in ws sheet, start from Cell A58
Set PTbl = ws.PivotTables.Add(PivotCache:=PCache, TableDestination:=Rng, TableName:="PivotTable5")
' rest of your code here
Else ' just refresh the Pivot table, with updated Pivot Cache
PTbl.ChangePivotCache PCache
PTbl.RefreshTable
End If
ActiveWorkbook.ShowPivotTableFieldList = True
End Sub

Related

I am unable to add Data Field to my Pivot Table VBA

I get a runtime error
Unable to get the PivotTables property of Worksheet class
when I run the following code:
Sub UpdatePivot()
Dim ws As Worksheet, SrcData As String, pvtCache As PivotCache
Dim ws2 As Worksheet, NR As Long, NC As Long, ws3 As Worksheet
Dim pf As PivotField, pt As PivotTable, df As PivotField, str As String
'Set ws = ThisWorkbook.Worksheets("Lisun Data")
Set ws2 = ThisWorkbook.Worksheets("Cover")
Set ws3 = ThisWorkbook.Worksheets("Stockist")
Set pt = ws3.PivotTables("PivotTable3")
Set pt = ws3.PivotTables("PivotTable3")
With pt.PivotFields(" May-17")
.Orientation = xlColumnField
.Function = xlSum
.Position = 1
End With
End Sub
May I know what is wrong?
I did add the data source to a data model beforehand, and I'm not sure what exactly is causing the error.
Try the code below to try and trap your errors, explanations inside the code's comments:
Option Explicit
Sub UpdatePivot()
Dim ws As Worksheet, SrcData As String, pvtCache As PivotCache
Dim ws2 As Worksheet, NR As Long, NC As Long, ws3 As Worksheet
Dim pf As PivotField, pt As PivotTable, df As PivotField, str As String
'Set ws = ThisWorkbook.Worksheets("Lisun Data")
Set ws2 = ThisWorkbook.Worksheets("Cover")
Set ws3 = ThisWorkbook.Worksheets("Stockist")
' 1ST: Trap the Pivot-Table object
On Error Resume Next
Set pt = ws3.PivotTables("PivotTable3")
On Error GoTo 0
If pt Is Nothing Then '<-- Pivot Table does't exist (Pivot Table renamed ?)
MsgBox "Pivot-Table object Error!"
Else ' Pivot-Table object exists
' 2NDT: Trap the PivotField object
On Error Resume Next
Set pf = pt.PivotFields(" May-17")
On Error GoTo 0
If pf Is Nothing Then
MsgBox "Pivot-Field object Error!"
Else
With pf
.Orientation = xlColumnField
.Function = xlSum
.Position = 1
End With
End If
End If
End Sub
Thank you to #Shai Rado for all your feedback, extremely valuable. Also big big thanks to #jeffreyweir, I recorded a macro and found out the answer that I needed. The code for adding any pivot field from a data model is below:
ActiveSheet.PivotTables("PivotTable3").AddDataField ActiveSheet.PivotTables( _
"PivotTable3").CubeFields("[Measures].[Sum of May-17]"), "Sum of May-17"

Copy worksheet and rename it and declare variable vBA

I am copying a worksheet and rename it using the cell values from 3rd sheet. THe only issue I am having is how do I declare the new sheet a a variable since i will be working on that sheet? I get an error saying "expected: end of statement" on the the last line.
Dim wsNew As Worksheet
Dim wsIntro As Worksheet
Dim wsUp As Worksheet
Set wsUp = Worksheets("Sheet1")
Set wsIntro = Worksheets("Instructions")
Worksheets("Sheet1").Copy after:=Sheets(Worksheets.Count)
With ActiveSheet.UsedRange
.Value = .Value
End With
ActiveSheet.name = wsIntro.Range("b6").Value & wsIntro.Range("b7").Value
Dim wsAllo As Worksheet
Set wsAllo = "wsIntro.Range("b6").Value & wsIntro.Range("b7").Value"
As the worksheet that you are trying to set a reference to is the ActiveSheet, you can simply change
Set wsAllo = "wsIntro.Range("b6").Value & wsIntro.Range("b7").Value"
to
Set wsAllo = ActiveSheet
Refactoring your code slightly gives:
Dim wsNew As Worksheet
Dim wsIntro As Worksheet
Dim wsUp As Worksheet
Dim wsAllo As Worksheet
Set wsUp = Worksheets("Sheet1")
Set wsIntro = Worksheets("Instructions")
'You shouldn't use "Sheets(Worksheets.Count)" - it will sometimes not do
'what you expect (when you have Charts as well as Worksheets in the Workbook)
'Use either "Sheets(Sheets.Count)" to place the new sheet as the last sheet
'in the workbook or use "Worksheets(Worksheets.Count)" to place the new sheet
'after the last worksheet in the workbook (but possibly with Charts after that)
wsUp.Copy After:=Sheets(Sheets.Count)
Set wsAllo = ActiveSheet
With wsAllo
.Name = wsIntro.Range("b6").Value & wsIntro.Range("b7").Value
.UsedRange.Value = .UsedRange.Value
End With

I get a Run-time Error #1004 for my VBA code with a Named range?

why does this code run fine:
Sub SelectRange()
Dim sourceBook As Workbook
Dim sourceSheet As Worksheet
Dim sourceSheetSum As Worksheet
Set sourceBook = ActiveWorkbook
Set sourceSheet = sourceBook.Sheets("Tabelle1")
ActiveWorkbook.Names.Add _
Name:="ggg", _
RefersTo:="=Sheet1!A4:L37"
sourceSheet.Select
sourceSheet.Range("A4:L37").Select
End Sub
However if I change
sourceSheet.Range("A4:L37").Select
to:
sourceSheet.Range("ggg").Select
I receive a run-time error 1004
Try the code below, it will create "ggg" named range from cells "A4:L37" in "Tabelle1" sheet.
Afterwards, it sets another Range MyNamedRange to the named Range("ggg") - this step is not necessary, I just like to work with variables for Range.
At the end, it selects MyNamedRange.
Code
Sub SelectRange()
Dim sourceBook As Workbook
Dim sourceSheet As Worksheet
Dim sourceSheetSum As Worksheet
Dim MyNamedRange As Range
Set sourceBook = ActiveWorkbook
Set sourceSheet = sourceBook.Sheets("Tabelle1")
' create the named range "ggg"
sourceBook.Names.Add _
Name:="ggg", _
RefersTo:="=" & sourceSheet.Name & "!A4:L37"
Set MyNamedRange = Range("ggg") ' <-- set the Range to your NamedRange "ggg"
sourceSheet.Activate '<-- activate the sheet first
MyNamedRange.Select '<-- select the Named Range
End Sub
Try this:
SourceSheet.Range(Names.Item("ggg")).Select

1004 error for using usedrange

I am trying to copy over values from one workbook to another using the usedrange function (there are some blanks in certain rows and it is fine to copy over the blank as well), but I am getting the 1004 error:
Sub ActiveInactiveVendors()
Dim ActiveWkb As Workbook, Wkb As Workbook, InactiveWkb As Workbook
Dim ActiveWkst As Worksheet, Wkst As Worksheet, InactiveWkst As Worksheet
Dim aCell As Range
Dim targetRng As Range
Set ActiveWkb = Workbooks.Open("C:\Users\clara\Desktop\active vendors.xlsx")
Set Wkb = ThisWorkbook
Set Wkst = Wkb.Sheets("Vendors")
Set ActiveWkst = ActiveWkb.Worksheets("aqlc7da48e7")
'set column A starting from A7
Set targetRng = Wkst.Range("A7" & Wkst.Rows.Count)
'get the values starting from a32 to the last row used and set it in wkst
targetRng.Value = ActiveWkst.Range("A32" & ActiveWkst.UsedRange.Rows.Count).Value
End Sub
I appreciate any feedback! Thank you
This line:
Set targetRng = Wkst.Range("A7" & Wkst.Rows.Count)
is not correct. You are not getting A7:A1048576 but a concatenating of the two. So it is looking for A71048576 which does not exist
Then you should use similar sized ranges when setting values.
Sub ActiveInactiveVendors()
Dim ActiveWkb As Workbook, Wkb As Workbook, InactiveWkb As Workbook
Dim ActiveWkst As Worksheet, Wkst As Worksheet, InactiveWkst As Worksheet
Dim aCell As Range
Dim targetRng As Range, origRng As Range
Set ActiveWkb = Workbooks.Open("C:\Users\clara\Desktop\active vendors.xlsx")
Set Wkb = ThisWorkbook
Set Wkst = Wkb.Sheets("Vendors")
Set ActiveWkst = ActiveWkb.Worksheets("aqlc7da48e7")
'set column A starting from A7
Set origRng = ActiveWkst.Range("A32", ActiveWkst.Cells(ActiveWkst.Rows.Count, 1).End(xlUp))
Set targetRng = Wkst.Range("A7", Wkst.Cells(origRng.Rows.Count + 6, 1))
'get the values starting from a32 to the last row used and set it in wkst
targetRng.Value = origRng.Value
End Sub

Copy specific entire column from file 1 to 2

Hello I'm trying to copy columns C, R, W,X from file 1 to file 2 with below code but keep getting an error. My VBA knowledge isn't that good yet but probably has to do with the range setting? I've tried multiple ways but can't get it to work.
Am I using the right setting or should I use another action to get the specific columns?
Sub PFS()
Dim wbCopy As Workbook
Dim wsCopy As Worksheet
Dim rngCopy As Range
Dim wbPaste As Workbook
Dim wsPaste As Worksheet
Dim rngPaste As Range
Set wbPaste = ActiveWorkbook
Set wbCopy = Workbooks.Open("path to copy")
Set wsCopy = wbCopy.Worksheets("Blad1")
Set rngCopy = wsCopy.Range("d, e").EntireColumn
Set wsPaste = wbPaste.Worksheets("PFS")
Set rngPaste = wsPaste.Range("a1")
rngCopy.Copy
rngPaste.PasteSpecial
Workbooks.Application.CutCopyMode = False
Application.DisplayAlerts = False
wbCopy.Save
wbCopy.Close
End Sub
Solutions to copy entire column.
Sub copy()
Dim wb As Workbook
Dim wbNew As Workbook
Dim ws As Worksheet
Dim wsNew As Worksheet
Set wb = ActiveWorkbook
Set ws = wb.Sheets("old")
Set wbNew = Workbooks("Book.xlsx")
Set wsNew = wbNew.Sheets("new")
ws.Columns(3).copy
wsNew.Columns(3).Insert Shift:=xlToRight
ws.Columns(18).copy
wsNew.Columns(18).Insert Shift:=xlToRight
ws.Columns(23).copy
wsNew.Columns(23).Insert Shift:=xlToRight
ws.Columns(24).copy
wsNew.Columns(24).Insert Shift:=xlToRight
Set wsNew = Nothing
Set wbNew = Nothing
Set ws = Nothing
Set wb = Nothing
End Sub