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
Related
I have a Vba code that is very slow on 25 sheets, I am wondering if this code can be speeded up in any way
Sub Obracun_place_OLP_NEAKTIVNO()
'
' Obracun_place_NOVI Makronaredba
'
Call Refresh_neto_TM
Application.ScreenUpdating = False
Sheets("PODUZEĆE_PLAĆA").Select
Range("B7:H7").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.ClearContents
Sheets("Neto plaća").Select
ActiveSheet.ListObjects("Tablica_Upit_iz_MS_Access_Database_14").Range. _
AutoFilter Field:=204, Criteria1:=Range("A2")
ActiveSheet.ListObjects("Tablica_Upit_iz_MS_Access_Database_14").Range. _
AutoFilter Field:=207, Criteria1:="<>"
Range("GV11:GZ11").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Sheets("PODUZEĆE_PLAĆA").Select
Range("B6:F6").Select
ActiveSheet.Paste
Sheets("Neto plaća").Select
Range("E11:F11").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Sheets("PODUZEĆE_PLAĆA").Select
Range("G6:H6").Select
ActiveSheet.Paste
Columns("B:H").Select
Columns("B:H").EntireColumn.AutoFit
Range("A2").Select
Sheets("Neto plaća").Select
ActiveSheet.ListObjects("Tablica_Upit_iz_MS_Access_Database_14").Range. _
AutoFilter Field:=207
ActiveSheet.ListObjects("Tablica_Upit_iz_MS_Access_Database_14").Range. _
AutoFilter Field:=204
Sheets("PODUZEĆE_PLAĆA").Select
Range("B5").Select
ActiveCell.FormulaR1C1 = "=COUNTIF((R[2]C:R[100]C),R[-4]C[-1])"
Range("E5").Select
ActiveCell.FormulaR1C1 = "=SUM(R[2]C:R[100]C)"
Range("E5").Select
Selection.AutoFill Destination:=Range("E5:F5"), Type:=xlFillDefault
Range("E5:F5").Select
Range("B6:H6").Select
Range(Selection, Selection.End(xlDown)).Select
ActiveWorkbook.Worksheets("PODUZEĆE_PLAĆA").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("PODUZEĆE_PLAĆA").Sort.SortFields.Add Key:=Range( _
"C7:C129"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortNormal
With ActiveWorkbook.Worksheets("PODUZEĆE_PLAĆA").Sort
.SetRange Range("B6:H129")
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Range("B7:H7").Select
Range(Selection, Selection.End(xlDown)).Select
With Selection.Interior
.Pattern = xlNone
.TintAndShade = 0
.PatternTintAndShade = 0
End With
Sheets("PLAĆA_SPISAK").Select
ActiveSheet.Range("$C$10:$G$60").AutoFilter Field:=1, Criteria1:="<>"
Sheets("PODUZEĆE_PLAĆA").Select
Range("B5").Select
Sheets("2001").Select
Range("A1").Select
Application.ScreenUpdating = True
End Sub
Getting Rid of Active and Select (Translating Macro-Recorder Code)
Not tested.
There is still much room for improvement but it should illustrate what it could look like.
It compiles but that doesn't mean it's gonna work. Give it a try and share some feedback.
Issues
If there is no match in the table, the code will fail.
If the data isn't 'nice' and has empty rows, the xlDown lines will fail.
Maybe it would be preferable to write the formulas in A1 style.
The Code
Option Explicit
Sub Obracun_place_OLP_NEAKTIVNO()
Application.ScreenUpdating = False
'Refresh_neto_TM '?
' Reference the workbook ('wb').
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
' Reference the source worksheet ('sws').
Dim sws As Worksheet: Set sws = wb.Worksheets("Neto plaća")
Dim stbl As ListObject
Set stbl = sws.ListObjects("Tablica_Upit_iz_MS_Access_Database_14")
' Reference the destination worksheet ('dws').
Dim dws As Worksheet: Set dws = wb.Worksheets("PODUZEĆE_PLAĆA")
' Clear the (old) destination data range (headers are in row 6).
With dws.Range("B7:H7")
.Range(.Cells, .End(xlDown)).ClearContents
End With
' Filter the source table.
With stbl
' Clear possible existing filters.
If .ShowAutoFilter Then
If .AutoFilter.FilterMode Then .AutoFilter.ShowAllData
Else
.ShowAutoFilter = True
End If
' Filter.
.Range.AutoFilter Field:=204, Criteria1:=CStr(sws.Range("A2").Value)
.Range.AutoFilter Field:=207, Criteria1:="<>"
End With
' Copy the data from the source to the destination worksheet.
With sws
With .Range("GV11:GZ11")
.Range(.Cells, .End(xlDown)).Copy dws.Range("B6:F6")
End With
With .Range("E11:F11")
.Range(.Cells, .End(xlDown)).Copy dws.Range("G6:H6")
End With
sws.Columns("B:H").EntireColumn.AutoFit
'Application.Goto sws.Range("A2") ' reset to initial selection
End With
' Clear the table filters.
stbl.AutoFilter.ShowAllData
With dws
' Reference the (new) destination range ('drg').
Dim drg As Range
With dws.Range("B6:H6")
Set drg = .Range(.Cells, .End(xlDown))
End With
' Write formulas.
Dim lfRow As Long: lfRow = drg.Rows.Count ' last formula row
.Range("B5").FormulaR1C1 _
= "=COUNTIF((R[2]C:R[" & lfRow & "]C),R[-4]C[-1])"
.Range("E5:F5").FormulaR1C1 = "=SUM(R[2]C:R[" & lfRow & "]C)"
' Sort by the 2nd column ('C').
With .Sort
.SortFields.Clear
.SortFields.Add _
Key:=drg.Columns(2), _
SortOn:=xlSortOnValues, _
Order:=xlAscending, _
DataOption:=xlSortNormal
.SetRange drg
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
' Apply formatting.
With drg.Resize(drg.Rows.Count - 1).Offset(1) ' 'drg' without headers
With .Interior
.Pattern = xlNone
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End With
'Application.Goto .Range("B5") ' reset to initial selection
End With
' These are irrelevant, the second one probably not necessary!?
wb.Worksheets("PLAĆA_SPISAK").Range("C10:G60").AutoFilter 1, "<>"
'Application.Goto wb.Worksheets("2001").Range("A1")
Application.ScreenUpdating = True
End Sub
I'm having issues with a macro that I've been using for months with little issue. The macro is designed to reformat an excel report and insert it into a different workbook within excel. Today, I keep encountering this message:
runtime error '9': subscript out of range
When I select Debug, it highlights this line of code:
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
I am not a coder. I've used the macro button to copy what I do to shorten tasks, but outside copy and pasting the errors and highlighted code into a search engine to see what someone else may have tried, I'm not savvy enough to troubleshoot the logic. The code has always worked, I've done nothing different, but today it's throwing that '9' error. What I have tried is renaming the worksheet to match the code, so basically "Sheet1". I have copied the previous month's worksheet, deleted the old data, and tried running the macro. I even tweaked the code as was suggested by a google find with an individual suffering a similar problem, but I just created a '1004' error because I don't totally understand the logic with xlTop vs. xlDown other than the implied direction. That didn't work so I'm back to square one.
Here is my macro code in total. It's simple enough.
Sub UserStats()
'
' UserStats Macro
'
Application.ScreenUpdating = False 'Doesn't show the macro
run on the screen, speeds up program
'
Cells.Select
With Selection
.VerticalAlignment = xlTop
.WrapText = True
.Orientation = 0
.AddIndent = False
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
Columns("A:A").Select
Selection.Delete Shift:=xlToLeft
Columns("B:C").Select
Selection.Delete Shift:=xlToLeft
Columns("C:D").Select
Selection.Delete Shift:=xlToLeft
Columns("D:I").Select
Selection.Delete Shift:=xlToLeft
Rows("1:7").Select
Selection.Delete Shift:=xlUp
Columns("A:D").Select
' SortUserStats Macro
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range("A1"), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortTextAsNumbers
With ActiveWorkbook.Worksheets("Sheet1").Sort
.SetRange Range("A:D")
.Header = xlNo
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
' CopyUserStats Macro
Cells.Select
Selection.RowHeight = 12
Range("A2:D2").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Workbooks("User Stats Prep.xlsx").Worksheets(1).Activate
Cells(Range("A1").End(xlDown).Row + 1, 1).Select
Selection.Insert Shift:=xlDown
Cells.Select
Selection.RowHeight = 12
Cells(Range("A1").End(xlDown).Row + 1, 1).Select
Application.CutCopyMode = False
ActiveWorkbook.Close SaveChanges:=True
ActiveWorkbook.Close SaveChanges:=False
End Sub
I appreciate any suggestions, otherwise I'll be adding the new data row by row copy and paste style.
I've tried to re-write it so that it doesn't have the excess that the macro recorder generally creates. If this does not work or if it works differently than before, please describe exactly what is wrong/the error
Sub UserStats()
'
' UserStats Macro
'
Application.ScreenUpdating = False 'hides screen, speeds up program
With ActiveWorkbook.Sheets(1)
'format all sheet1 cells
With .Cells
.VerticalAlignment = xlTop
.WrapText = True
.Orientation = 0
.AddIndent = False
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
.RowHeight = 12
End With
'delete A:D, D:I, and 1:7
.Columns("A:D").Delete Shift:=xlToLeft
.Columns("D:I").Delete Shift:=xlToLeft
.Rows("1:7").Delete Shift:=xlUp
'Sort UserStats
With .Columns("A:D").Sort
.SortFields.Clear
.SortFields.Add _
key:=Range("A1"), _
SortOn:=xlSortOnValues, _
Order:=xlAscending, _
DataOption:=xlSortTextAsNumbers
.SetRange Range("A:D")
.Header = xlNo
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
'Copy UserStats
ActiveWorkbook.Sheets(1).Range(Range("A2:D2"), Range("A2:D2").End(xlDown)).copy
End With
With Workbooks("User Stats Prep.xlsx").Worksheets(1)
.Cells.RowHeight = 12
.Cells(Range("A1").End(xlDown).row + 1, 1).Insert Shift:=xlDown
End With
Workbooks("User Stats Prep.xlsx").Close SaveChanges:=True
With Application
.CutCopyMode = False
.ScreenUpdating = True
End With
End Sub
I'm new at VBA and Macros. Following Macro Recording, I ended up with this bug.
The file name is available on desktop with the correct name.
Thanks for any help,
Sub Macro2435Pivot()
'
' Macro2435Pivot Macro
'
'
Cells.Select
Sheets.Add
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"2435_Monthly Sales with Adjustm'!1:15000", Version:=xlPivotTableVersion15). _
CreatePivotTable TableDestination:="Sheet2!R3C1", TableName:= _
"PivotTable" & [=round(Rand()*1000,0)], DefaultVersion:=xlPivotTableVersion15
Sheets("Sheet2").Select
Cells(3, 1).Select
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Month")
.Orientation = xlPageField
.Position = 1
End With
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
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