If possible I would like the macro below to run the same way, regardless of what the name of the sheet is. For instance on this file it's "ZPPV Final for March 2015". But that March, may change to April or May, etc. Can I have this macro run regardless of what month is on that sheets tab? Please see below:
Sub PPV()
'
' PPV Macro
'
'
Sheets("ZPPV Final for March 2015").Select
Range("Z3").Select
ActiveCell.FormulaR1C1 = "Week"
Range("Z4").Select
ActiveCell.FormulaR1C1 = "=WEEKNUM(RC[-9])"
Range("Z4").Select
Selection.AutoFill Destination:=Range("Z4:Z8858")
Range("Z4:Z8858").Select
Range("Z3").Select
Range(Selection, Selection.End(xlToLeft)).Select
Range(Selection, Selection.End(xlDown)).Select
Sheets.Add
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"***ZPPV Final for March 2015***!R3C2:R8858C26", Version:=xlPivotTableVersion14). _
CreatePivotTable TableDestination:="Sheet2!R3C1", TableName:="PivotTable9" _
, DefaultVersion:=xlPivotTableVersion14
Sheets("Sheet2").Select
Cells(3, 1).Select
With ActiveSheet.PivotTables("PivotTable9").PivotFields("Plant")
.Orientation = xlPageField
.Position = 1
End With
With ActiveSheet.PivotTables("PivotTable9").PivotFields("Week")
.Orientation = xlRowField
.Position = 1
End With
ActiveSheet.PivotTables("PivotTable9").AddDataField ActiveSheet.PivotTables( _
"PivotTable9").PivotFields(" PPV"), "Sum of PPV", xlSum
ActiveSheet.PivotTables("PivotTable9").PivotFields("Plant").ClearAllFilters
ActiveSheet.PivotTables("PivotTable9").PivotFields("Plant").CurrentPage = _
"1027"
Sheets("**ZPPV Final for March 2015").**Select
ActiveWorkbook.Worksheets("Sheet2").PivotTables("PivotTable9").PivotCache. _
CreatePivotTable TableDestination:="Sheet2!R1C6", TableName:="PivotTable10" _
, DefaultVersion:=xlPivotTableVersion14
Sheets("Sheet2").Select
Cells(1, 6).Select
With ActiveSheet.PivotTables("PivotTable10").PivotFields("Plant")
.Orientation = xlPageField
.Position = 1
End With
With ActiveSheet.PivotTables("PivotTable10").PivotFields("Week")
.Orientation = xlRowField
.Position = 1
End With
ActiveSheet.PivotTables("PivotTable10").AddDataField ActiveSheet.PivotTables( _
"PivotTable10").PivotFields(" PPV"), "Sum of PPV", xlSum
With ActiveSheet.PivotTables("PivotTable10").PivotFields("Vendor Name")
.Orientation = xlRowField
.Position = 1
End With
Range("F4").Select
ActiveSheet.PivotTables("PivotTable10").PivotFields("Vendor Name").ShowDetail _
= False
ActiveSheet.PivotTables("PivotTable10").PivotFields("Plant").ClearAllFilters
ActiveSheet.PivotTables("PivotTable10").PivotFields("Plant").CurrentPage = _
"1027"
Sheets("ZPPV Final for March 2015").Select
ActiveWorkbook.Worksheets("Sheet2").PivotTables("PivotTable10").PivotCache. _
CreatePivotTable TableDestination:="Sheet2!R1C10", TableName:= _
"PivotTable11", DefaultVersion:=xlPivotTableVersion14
Sheets("Sheet2").Select
Cells(1, 10).Select
With ActiveSheet.PivotTables("PivotTable11").PivotFields("Plant")
.Orientation = xlPageField
.Position = 1
End With
ActiveSheet.PivotTables("PivotTable11").AddDataField ActiveSheet.PivotTables( _
"PivotTable11").PivotFields(" PPV"), "Sum of PPV", xlSum
With ActiveSheet.PivotTables("PivotTable11").PivotFields("Material No.")
.Orientation = xlRowField
.Position = 1
End With
ActiveSheet.PivotTables("PivotTable11").PivotFields("Plant").ClearAllFilters
ActiveSheet.PivotTables("PivotTable11").PivotFields("Plant").CurrentPage = _
"1027"
Range("A3").Select
ActiveSheet.PivotTables("PivotTable9").CompactLayoutRowHeader = "Week"
Range("F3").Select
ActiveSheet.PivotTables("PivotTable10").CompactLayoutRowHeader = "Vendor"
Range("J3").Select
ActiveSheet.PivotTables("PivotTable11").CompactLayoutRowHeader = _
"Material Number"
Range("A2").Select
ActiveCell.FormulaR1C1 = "PPV By Week"
Range("F2").Select
ActiveCell.FormulaR1C1 = "PPV By Vendor"
Range("J2").Select
ActiveCell.FormulaR1C1 = "PPV By Material #"
Range("J2").Select
Selection.Font.Bold = True
Range("F2").Select
Selection.Font.Bold = True
Range("A2").Select
Selection.Font.Bold = True
Range("D3").Select
End Sub
Here's a quick example
Dim sh as worksheet
Dim ws as worksheet
set ws=sheets("Sheet2")
set sh=activesheet
sh.Range("Z3") = "Week"
with ws
'do something
end with
If there is only one worksheet in your workbook, then use the index.
Dim ws As Worksheet ' Declare a worksheet type variable
Set ws = Thisworksbook.Sheets(1) ' assign the worksheet object
If there are other worksheets but the same worksheet is used all throughout (meaning, the sheet name is just edited for the new month) then use the worksheet codename.
Dim ws As Worksheet ' Declare a worksheet type variable
Set ws = Sheet1 ' use Codename to assign worksheet object to variable
You can only edit the Codename in the properties window as shown above.
The user can change the sheet name outside but not the Codename.
If a new sheet is created for every month, use a loop.
Dim ws As Worksheet, i As Integer
Dim MoYr As String
MoYr = Format(Date, "mmmm yyyy") ' Returns April 2015 if run now
With ThisWorkbook
For i = 1 To .Sheets.Count
If InStr(.Sheets(i).Name, MoYr) <> 0 Then
Set ws = .Sheets(i): Exit For
End If
Next
End With
If ws Is Nothing Then Exit Sub ' Just in case nothing is found
Related
I recorded a macro that makes some pivot tables in a new sheet and it works fine, so i tried to make it able to overwrite if the sheet already existed but i can't seem to make it work. The problem is that when i use the macro once it does add the new sheet but it also adds another one on top of the one already made, and when i try to use the macro again to see if it overwrites the other one, it doesn't it just adds another unnamed sheet.
The code looks like this:
Sub Makro7()
Sheets.Add After:=ActiveSheet
On Error Resume Next
Sheets.Add().Name = "Statistics"
On Error GoTo 0
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"Base!R1C1:R18288C12", Version:=6).CreatePivotTable TableDestination:= _
"Statistics!R1C1", TableName:="Pivottabel22", DefaultVersion:=6
Sheets("Statistics").Select
Cells(1, 1).Select
ActiveSheet.PivotTables("Pivottabel22").AddDataField ActiveSheet.PivotTables( _
"Pivottabel22").PivotFields("FACULTY_ID"), "Antal af FACULTY_ID", xlCount
With ActiveSheet.PivotTables("Pivottabel22").PivotFields("FACULTY_ID")
.Orientation = xlColumnField
.Position = 1
End With
With ActiveSheet.PivotTables("Pivottabel22").PivotFields("PROGRAM_TYPE_NAME")
.Orientation = xlRowField
.Position = 1
End With
Range("A1").Select
ActiveSheet.PivotTables("Pivottabel22").DataPivotField.PivotItems( _
"Antal af FACULTY_ID").Caption = "Antal"
Range("B1").Select
ActiveSheet.PivotTables("Pivottabel22").CompactLayoutColumnHeader = "Fakultet"
Range("A7").Select
ActiveWorkbook.Worksheets("Statistics").PivotTables("Pivottabel22").PivotCache. _
CreatePivotTable TableDestination:="Statistics!R7C1", TableName:= _
"Pivottabel23", DefaultVersion:=6
Sheets("Statistics").Select
Cells(7, 1).Select
ActiveSheet.PivotTables("Pivottabel23").AddDataField ActiveSheet.PivotTables( _
"Pivottabel23").PivotFields("FACULTY_ID"), "Antal af FACULTY_ID", xlCount
With ActiveSheet.PivotTables("Pivottabel23").PivotFields("PROGRAM_TYPE_NAME")
.Orientation = xlRowField
.Position = 1
End With
With ActiveSheet.PivotTables("Pivottabel23").PivotFields("FACULTY_ID")
.Orientation = xlColumnField
.Position = 1
End With
With ActiveSheet.PivotTables("Pivottabel23").PivotFields("Antal af FACULTY_ID")
.Calculation = xlPercentOfTotal
.NumberFormat = "0.00%"
End With
Range("A7").Select
ActiveSheet.PivotTables("Pivottabel23").DataPivotField.PivotItems( _
"Antal af FACULTY_ID").Caption = "Procentvis"
Range("B7").Select
ActiveSheet.PivotTables("Pivottabel23").CompactLayoutColumnHeader = "Fakultet"
Range("A13").Select
ActiveWorkbook.Worksheets("Statistics").PivotTables("Pivottabel23").PivotCache. _
CreatePivotTable TableDestination:="Statistics!R13C1", TableName:= _
"Pivottabel24", DefaultVersion:=6
Sheets("Statistics").Select
Cells(13, 1).Select
ActiveSheet.PivotTables("Pivottabel24").AddDataField ActiveSheet.PivotTables( _
"Pivottabel24").PivotFields("ENROLL_LOCATION_NAME"), _
"Antal af ENROLL_LOCATION_NAME", xlCount
With ActiveSheet.PivotTables("Pivottabel24").PivotFields("ENROLL_LOCATION_NAME" _
)
.Orientation = xlRowField
.Position = 1
End With
Range("B13").Select
ActiveSheet.PivotTables("Pivottabel24").DataPivotField.PivotItems( _
"Antal af ENROLL_LOCATION_NAME").Caption = "Antal"
Range("A13").Select
ActiveSheet.PivotTables("Pivottabel24").CompactLayoutRowHeader = "Campus"
Range("B13").Select
ActiveSheet.PivotTables("Pivottabel24").DataPivotField.PivotItems("Antal"). _
Caption = "Antal af studerende"
Range("A22").Select
ActiveWorkbook.Worksheets("Statistics").PivotTables("Pivottabel24").PivotCache. _
CreatePivotTable TableDestination:="Statistics!R22C1", TableName:= _
"Pivottabel25", DefaultVersion:=6
Sheets("Statistics").Select
Cells(22, 1).Select
ActiveSheet.PivotTables("Pivottabel25").AddDataField ActiveSheet.PivotTables( _
"Pivottabel25").PivotFields("ENROLL_LOCATION_NAME"), _
"Antal af ENROLL_LOCATION_NAME", xlCount
With ActiveSheet.PivotTables("Pivottabel25").PivotFields("ENROLL_LOCATION_NAME" _
)
.Orientation = xlRowField
.Position = 1
End With
With ActiveSheet.PivotTables("Pivottabel25").PivotFields( _
"Antal af ENROLL_LOCATION_NAME")
.Calculation = xlPercentOfTotal
.NumberFormat = "0.00%"
End With
Range("A22").Select
ActiveSheet.PivotTables("Pivottabel25").CompactLayoutRowHeader = "Campus"
Range("B22").Select
ActiveSheet.PivotTables("Pivottabel25").DataPivotField.PivotItems( _
"Antal af ENROLL_LOCATION_NAME").Caption = "Procentvis af studerende"
Range("I1").Select
ActiveWorkbook.Worksheets("Statistics").PivotTables("Pivottabel25").PivotCache. _
CreatePivotTable TableDestination:="Statistics!R1C9", TableName:= _
"Pivottabel26", DefaultVersion:=6
Sheets("Statistics").Select
Cells(1, 9).Select
ActiveSheet.PivotTables("Pivottabel26").AddDataField ActiveSheet.PivotTables( _
"Pivottabel26").PivotFields("STUDYBOARD_ID"), "Antal af STUDYBOARD_ID", xlCount
With ActiveSheet.PivotTables("Pivottabel26").PivotFields("STUDYBOARD_ID")
.Orientation = xlRowField
.Position = 1
End With
Range("I1").Select
ActiveSheet.PivotTables("Pivottabel26").CompactLayoutRowHeader = "Studienævn"
Range("J1").Select
ActiveSheet.PivotTables("Pivottabel26").DataPivotField.PivotItems( _
"Antal af STUDYBOARD_ID").Caption = "Antal af studerende"
Range("L15").Select
End Sub
The problem is this piece of code:
Sheets.Add After:=ActiveSheet
On Error Resume Next
Sheets.Add().Name = "Statistics"
On Error GoTo 0
This basically tells Excel to add a new sheet after the active sheet and when you run the macro the second time, the sheetname "Statistics" is already taken. (And if it wasn't for On error resume next, an error message would appear the second time). Add this at the top of your macro instead:
Dim newSheet As Worksheet
Application.DisplayAlerts = False
Set newSheet = Sheets.Add(After:=ActiveSheet)
With newSheet
On Error Resume Next
ThisWorkbook.Sheets("Statistics").Delete
On Error GoTo 0
.name = "Statistics"
End With
Application.DisplayAlerts = True
I recorded a macro in which I want to create a pivot table into a new worksheet. I am using 2010 version.
I have the "Run time error 5" Invalid procedure call or argument" error when I want to run a macro. Please see the code. It creates the new sheet so is it not fine?
Range("A1").Select
Sheets.Add
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"Sheet1!R1C1:R17445C24", Version:=xlPivotTableVersion12).CreatePivotTable _
TableDestination:="Sheet4!R3C1", TableName:="PivotTable1", DefaultVersion _
:=xlPivotTableVersion12
Sheets("Sheet4").Select
Cells(3, 1).Select
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Bnlunit")
.Orientation = xlPageField
.Position = 1
End With
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Period")
.Orientation = xlColumnField
.Position = 1
End With
ActiveWindow.SmallScroll Down:=12
ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables( _
"PivotTable1").PivotFields("Amount"), "Sum of Amount", xlSum
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Hdaccount_agr_3(T)")
.Orientation = xlRowField
.Position = 1
End With
ActiveWindow.SmallScroll Down:=-33
End Sub
The problem is because of sheet name and not deleting those sheets. I think the below code could be of your help
Sub Macro1()
'
Dim PSheet As Worksheet
Dim DSheet As Worksheet
Dim PCache As PivotCache
Dim PTable As PivotTable
Dim PRange As Range
Dim LastRow As Long
Dim LastCol As Long
'Delete Preivous Pivot Table Worksheet & Insert a New Blank Worksheet With Same Name
On Error Resume Next
Application.DisplayAlerts = False
Worksheets("PivotTable").Delete
Sheets.Add Before:=ActiveSheet
ActiveSheet.Name = "PivotTable"
Application.DisplayAlerts = True
Set PSheet = Worksheets("PivotTable")
Set DSheet = Worksheets("Raw Data")
'Define Data Range
LastRow = DSheet.Cells(Rows.Count, 1).End(xlUp).Row
LastCol = DSheet.Cells(1, Columns.Count).End(xlToLeft).Column
Set PRange = DSheet.Cells(1, 1).Resize(LastRow, LastCol)
'Define Pivot Cache
Set PCache = ActiveWorkbook.PivotCaches.Create _
(SourceType:=xlDatabase, SourceData:=PRange). _
CreatePivotTable(TableDestination:=PSheet.Cells(2, 2), _
TableName:="PRIMEPivotTable")
'Insert Blank Pivot Table
Set PTable = PCache.CreatePivotTable_(TableDestination:=PSheet.Cells(1, 1), TableName:="PRIMEPivotTable")
'Insert Column Fields
'With ActiveSheet.PivotTables("PRIMEPivotTable").PivotFields("ColumnName")
'.Orientation = xlColumnField
'.Position = 1
'End With
'Insert Row Fields
With ActiveSheet.PivotTables("PRIMEPivotTable").PivotFields("RowName")
.Orientation = xlRowField
.Position = 1
End With
'Insert Data Field
With ActiveSheet.PivotTables("PRIMEPivotTable").PivotFields("Field 1")
.Orientation = xlDataField
.Position = 1
.Function = xlCount
.Name = "Name of your choice"
End With
End Sub
Try the code below, explanations inside the code's comments:
Option Explicit
Sub VBAPivot()
Dim Sht1 As Worksheet
Dim NewSht As Worksheet
Dim PvtCache As PivotCache
Dim PvtTbl As PivotTable
Dim PvtRange As Range
Dim LastRow As Long
Set NewSht = ThisWorkbook.Sheets.Add ' add new sheet
Set Sht1 = ThisWorkbook.Worksheets("Sheet1")
With Sht1
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
' set the PivotCach DataSource Range
Set PvtRange = .Range("A1:X" & LastRow)
End With
' Set the Pivot Cache
Set PvtCache = ActiveWorkbook.PivotCaches.Create(xlDatabase, PvtRange.Address(False, False, xlA1, xlExternal))
' create a new Pivot Table in the new added sheet, in "A3"
Set PvtTbl = NewSht.PivotTables.Add(PivotCache:=PvtCache, TableDestination:=NewSht.Range("A3"), TableName:="PivotTable1")
With PvtTbl ' modify Pivot-Table properties
With .PivotFields("Bnlunit")
.Orientation = xlPageField
.Position = 1
End With
With .PivotFields("Period")
.Orientation = xlColumnField
.Position = 1
End With
' add Field as Sum of
.AddDataField .PivotFields("Amount"), "Sum of Amount", xlSum
With .PivotFields("Hdaccount_agr_3(T)")
.Orientation = xlRowField
.Position = 1
End With
End With
End Sub
I created this code with macro recorder to get Pivot table automatically.
But when I run this code again an error message appears:
Run-time error 1004: Invalid reference
at this line Workbooks("works.xlsm").Connections.Add2.
Why is there invalid reference if this code was recorded? During the recording, I gave the name "database" for the table (R1C4:R18532C9). I use Windows 10 and Office 2016.
Range("D1").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
ActiveWorkbook.Names.Add Name:="database", RefersToR1C1:= _
"=Data!R1C4:R18532C9"
ActiveWorkbook.Names("database").Comment = ""
Range("D1").Select
Workbooks("works.xlsm").Connections.Add2 _
"WorksheetConnection_works.xlsm!database", "", _
"WORKSHEET;C:\Users\gabor\Documents\CAFM\VBS\works.xlsm", _
"works.xlsm!database", 7, True, False
ActiveWorkbook.PivotCaches.Create(SourceType:=xlExternal, SourceData:= _
ActiveWorkbook.Connections("WorksheetConnection_works.xlsm!database"), _
Version:=6).CreatePivotTable TableDestination:="Pivot!R1C1", TableName:= _
"Statement1", DefaultVersion:=6
Sheets("Pivot").Select
Cells(1, 1).Select
With ActiveSheet.PivotTables("Statement1").CubeFields("[database].[Person]")
.Orientation = xlRowField
.Position = 1
End With
The database table and the pivot results with xlCount and xlDistinctCount
Try edited code below, explanations are inside the code as comments.
xlDistinctCount is untested as I have Office 2010 (it's available from Officde 2013), but should work.
Code
Option Explicit
Sub AutoDynamicPivot()
Dim PT As PivotTable
Dim PTCache As PivotCache
Dim WB As Workbook
Dim Sht As Worksheet
Dim SrcData As Variant
Dim lRow As Long, lCol As Long
Set WB = ThisWorkbook
Set Sht = WB.Worksheets("Data") '<-- set the "Data" worksheet
lRow = Sht.Range("A1").End(xlDown).Row '<-- modifed from "D1" to "A1" (according to PO screen-shot)
lCol = Sht.Range("A1").End(xlToRight).Column '<-- modifed from "D1" to "A1" (according to PO screen-shot)
' set the Named Range "database" to the data in worksheet "Data"
WB.Names.Add Name:="database", RefersToR1C1:="=" & Sht.Name & "!R1C1:R" & lRow & "C" & lCol '<-- modifed to "R1C1" (according to PO screen-shot)
WB.Names("database").Comment = ""
' Determine the data range you want for your Pivot Cache
Set SrcData = Range("database")
' set the Pivot Cache
Set PTCache = ActiveWorkbook.PivotCaches.Add(xlDatabase, SrcData)
' add this line in case the Pivot table doesn't exit >> first time running this Macro
On Error Resume Next
Set PT = Worksheets("Pivot").PivotTables("Statement1") ' check if "Statement1" Pivot Table already created (in past runs of this Macro)
On Error GoTo 0
If PT Is Nothing Then
' create a new Pivot Table in "Pivot" sheet, start from Cell A1
Set PT = Worksheets("Pivot").PivotTables.Add(PivotCache:=PTCache, TableDestination:=Worksheets("Pivot").Range("A1"), TableName:="Statement1")
'Create the headings and row and column orientation and all of your other settings here
With PT
' set "Person" as rows field
With .PivotFields("Person")
.Orientation = xlRowField
.Position = 1
End With
' set "Month" as Filter
With .PivotFields("Month")
.Orientation = xlPageField
.Position = 1
End With
' set "Count of Cases"
.AddDataField .PivotFields("Case"), "Count of Case", xlCount
' set "Distinct Count of Cases"
.AddDataField .PivotFields("Case"), "Distinct Count of Case", xlDistinctCount
End With
Else
' just refresh the Pivot cache with the updated Range (data in "Data" worksheet)
PT.ChangePivotCache PTCache
PT.RefreshTable
End If
End Sub
Screen-shot of the Pivot-Table created with this code:
I changed the commandtext parameter in Connections.Add2 from "works.xlsm!database" to "Data!database". It solved the problem. I edited the ActiveWorkbook.Names.Add as well.
LastRow = Sheets("Data").Cells(Rows.Count, 1).End(xlUp).Row
LastCol = Sheets("Data").Cells(1, Columns.Count).End(xlToLeft).Column
ActiveWorkbook.Names.Add _
Name:="database", _
RefersTo:="=Data!R1C4:R" & LastRow & "C" & LastCol & ""
ActiveWorkbook.Connections.Add2 _
"WorksheetConnection_works.xlsm!database", "", _
"WORKSHEET;C:\Users\gabor\Documents\CAFM\VBS\works.xlsm", _
"Data!database", 7, True, False
ActiveWorkbook.PivotCaches.Create(SourceType:=xlExternal, SourceData:= _
ActiveWorkbook.Connections("WorksheetConnection_works.xlsm!database"), _
Version:=6).CreatePivotTable TableDestination:="Pivot!R1C1", TableName:= _
"Statement1", DefaultVersion:=6
Sheets("Pivot").Select
Cells(1, 1).Select
With ActiveSheet.PivotTables("Statement1").CubeFields("[database].[Person]")
.Orientation = xlRowField
.Position = 1
End With
I could get the xlDistinctCount with this code:
ActiveSheet.PivotTables("Statement1").CubeFields.GetMeasure "[database].[TT]" _
, xlCount
ActiveSheet.PivotTables("Statement1").AddDataField ActiveSheet.PivotTables( _
"Statement1").CubeFields("[Measures].[quantity of items - TT]")
With ActiveSheet.PivotTables("Statement1").PivotFields( _
"[Measures].[quantity of items - TT]")
.Caption = "number of distinct items – TT"
.Function = xlDistinctCount
End With
I had to use the xlCount first and with this result could I get the xlDistinctCount.
I'm trying to create my first VBA code to basically:
-select a cell
-sort the column by A-Z
-pivot the data
-create a line chart
-re-size the chart to make it bigger
I'm getting a runtime error 9 message subscript out of range and it highlights the following line
ActiveWorkbook.Worksheets("advertiserConversionReport_3045").Sort.SortFields. _
Clear
What I did was to open another workbook and tried to run the macro on the data.
Looking through the code (I'm not a developer) I'm seeing that the errors could be the reference to the initial workbook advertiserConversionReport_3045 and perhaps a previously set range for the pivot Range("A2:F97")
Sub ActionReport()
'
' ActionReport Macro
' This macro will pivot data from the action report and create a line chart to show trending of credited conversions by day.
'
' Keyboard Shortcut: Ctrl+shift+a
'
Range("B1").Select
ActiveWorkbook.Worksheets("advertiserConversionReport_3045").Sort.SortFields. _
Clear
ActiveWorkbook.Worksheets("advertiserConversionReport_3045").Sort.SortFields. _
Add Key:=Range("B1"), SortOn:=xlSortOnValues, Order:=xlAscending, _
DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("advertiserConversionReport_3045").Sort
.SetRange Range("A2:F97")
.Header = xlNo
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Sheets.Add
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"advertiserConversionReport_3045!R1C1:R97C6", Version:=xlPivotTableVersion14) _
.CreatePivotTable TableDestination:="Sheet1!R3C1", TableName:="PivotTable1" _
, DefaultVersion:=xlPivotTableVersion14
Sheets("Sheet1").Select
Cells(3, 1).Select
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Day")
.Orientation = xlRowField
.Position = 1
End With
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Conversion Action")
.Orientation = xlRowField
.Position = 2
End With
ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables( _
"PivotTable1").PivotFields("Credited Conversions"), _
"Sum of Credited Conversions", xlSum
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Conversion Action")
.Orientation = xlColumnField
.Position = 1
End With
ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlLineMarkers
ActiveChart.SetSourceData Source:=Range("Sheet1!$A$3:$R$11")
ActiveWorkbook.ShowPivotTableFieldList = False
ActiveSheet.Shapes("Chart 1").ScaleWidth 1.6583333333, msoFalse, _
msoScaleFromTopLeft
ActiveSheet.Shapes("Chart 1").ScaleHeight 1.7065974045, msoFalse, _
msoScaleFromTopLeft
ActiveWindow.SmallScroll Down:=-24
ActiveSheet.Shapes("Chart 1").IncrementLeft -38.25
ActiveSheet.Shapes("Chart 1").IncrementTop -81.75
End Sub`
Does anyone know how to fix this and execute the macro successfully?
You are getting that error because the "Activeworkbook" doesn't have the sheet called "advertiserConversionReport_3045".
Avoid using ActiveWorkbook. Create Objects and then work with them. You may want to see this link
Try something like this
Sub Sample()
Dim thiswb As Workbook, wbNew As Workbook
Set thiswb = ThisWorkbook
'~~> Change as applicable
Set wbNew = Workbooks.Open("C:\Sample.xlsm")
With wbNew
.Worksheets("advertiserConversionReport_3045").Sort.SortFields.Clear
End With
End Sub
I am trying to record a macro which will create pivot chart out of excel data and here is the code that has been recorded:
Sub chart1()
'
' chart1 Macro
'
'
Range("E1:F11").Select
Sheets.Add
In Debugger, code within the **** **** is shown in Yellow color
***** ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"data!R1C5:R11C6", Version:=xlPivotTableVersion12).CreatePivotTable _
TableDestination:="Sheet1!R3C1", TableName:="PivotTable1", DefaultVersion _
:=xlPivotTableVersion12 ********
Sheets("Sheet1").Select
Cells(3, 1).Select
With ActiveSheet.PivotTables("PivotTable1").PivotFields("question1")
.Orientation = xlRowField
.Position = 1
End With
With ActiveSheet.PivotTables("PivotTable1").PivotFields("answer1")
.Orientation = xlColumnField
.Position = 1
End With
ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables( _
"PivotTable1").PivotFields("answer1"), "Count of answer1", xlCount
With ActiveSheet.PivotTables("PivotTable1").PivotFields("answer1")
.Orientation = xlPageField
.Position = 1
End With
ActiveSheet.PivotTables("PivotTable1").PivotFields("answer1").Orientation = _
xlHidden
With ActiveSheet.PivotTables("PivotTable1").PivotFields("answer1")
.Orientation = xlColumnField
.Position = 1
End With
ActiveSheet.Shapes.AddChart.Select
ActiveChart.SetSourceData Source:=Range("Sheet1!$A$3:$D$6")
ActiveSheet.Shapes.AddChart.Select
ActiveChart.SetSourceData Source:=Range("Sheet1!$A$3:$D$6")
ActiveChart.ChartType = xlColumnClustered
End Sub
Why am I getting the Run Time Error 1004: Application-Defined or Object Defined Error when i try to run this macro ?
Thanks in advance..
Since you want the chart to be on a new sheet,
you have to change the macro's "Sheet1" to new worksheet's name,
The following macro should work for you, I have named the new worksheet as newWs
And fyi, your macro's error message I believe is due to trying to creating 2 pivot table of the same name on "Sheet1" is not allowed.
He also like to know what to create pivotTable base on Selected Area, so I have done modification to the code.
Edited: I Assume you select 2 columns each time
Sub chart1()
'
' chart1 Macro
'
'
Dim selectedSheetName As String
Dim newWs As Worksheet
Dim rangeName As String
Dim header1 As String
Dim header2 As String
header1 = ActiveSheet.Cells(1, Selection.Column).Value
header2 = ActiveSheet.Cells(1, Selection.Column + 1).Value
selectedSheetName = ActiveSheet.Name
rangeName = Selection.Address
Set newWs = Sheets.Add
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
selectedSheetName & "!" & rangeName, Version:=xlPivotTableVersion12).CreatePivotTable _
TableDestination:=newWs.Name & "!R3C1", TableName:="PivotTable1", DefaultVersion _
:=xlPivotTableVersion12
newWs.Activate
Cells(3, 1).Select
With ActiveSheet.PivotTables("PivotTable1").PivotFields(header1)
.Orientation = xlRowField
.Position = 1
End With
With ActiveSheet.PivotTables("PivotTable1").PivotFields(header2)
.Orientation = xlColumnField
.Position = 1
End With
ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables( _
"PivotTable1").PivotFields(header2), "Count of answer1", xlCount
With ActiveSheet.PivotTables("PivotTable1").PivotFields(header2)
.Orientation = xlPageField
.Position = 1
End With
ActiveSheet.PivotTables("PivotTable1").PivotFields(header2).Orientation = _
xlHidden
With ActiveSheet.PivotTables("PivotTable1").PivotFields(header2)
.Orientation = xlColumnField
.Position = 1
End With
ActiveSheet.Shapes.AddChart.Select
ActiveChart.SetSourceData Source:=Range(newWs.Name & "!$A$3:$D$6")
ActiveSheet.Shapes.AddChart.Select
ActiveChart.SetSourceData Source:=Range(newWs.Name & "!$A$3:$D$6")
ActiveChart.ChartType = xlColumnClustered
End Sub