I am programming an excel application that takes info from a Tables Sheet ( that it is also programmed and the length and position of each table can change) and generate a graphic for each table in other sheet, called Estimation Sheet, when a button is press.
I managed to do this task for the first graphich (corresponding to first table) but when I try to use the same method for the second...it doesn't work. This is the method used to draw the first graphic:
Public Sub generateGraphicsC(RowResistiveC As Integer)
Dim FirstRow As Integer, FirstColumn As Integer, LastRow As Integer, LastColumn As Integer, GraphLocation As Integer
Dim XelementsC As Integer, Yelements As Integer
Dim myChtObj As ChartObject
Dim rngChtData As Range
Dim rngChtXVal As Range
Dim i As Integer
Dim WSD As Worksheet
Set WSD = Worksheets(2) 'Data source
Dim CSD As Worksheet
Set CSD = Worksheets(3) 'ChartOutput
'Dim chrt As ChartObject
'Dim cw As Long
'Dim rh As Long
' get the current charts so proper overwriting can happen Dim chtObjs As ChartObjects
Set chtObjs = CSD.ChartObjects
WSD.AutoFilterMode = False ' Turn off autofilter mode
'Dim finalRow As Long ' Find the last row with data
'finalRow = WSD.Cells(Application.Rows.Count, 1).End(xlUp).Row
FirstRow = RowResistiveC
FirstColumn = 5
XelementsC = countXelementsC(FirstRow - 1, FirstColumn) 'Count the x Elements (amperes)
Yelements = countYelements(FirstRow) 'Count the y Elements (Combinations)
LastRow = FirstRow + Yelements - 1 'The last row and column I will read
LastColumn = FirstColumn + XelementsC - 1
'---------------------DRAW THE GRAPHIC----------------------------------------------'
' Delete any previous existing chart
'Dim chtObj As ChartObject
' define the x axis values
WSD.Activate
Set rngChtXVal = WSD.Range(Cells(FirstRow - 1, FirstColumn), Cells(FirstRow - 1, LastColumn))
' add the chart
Charts.Add
With ActiveChart
' make a XY chart
.ChartType = xlXYScatterLines
' remove extra series
Do Until .SeriesCollection.Count = 0
.SeriesCollection(1).Delete
Loop
.Location Where:=xlLocationAsObject, Name:="Estimation Sheets"
End With
'-----------------------------------------------------------------------------
With ActiveChart
.HasTitle = True
.ChartTitle.Characters.Text = "Factor C"
'To Interpolate between the ungiven values
.DisplayBlanksAs = xlInterpolated
'TITLE STYLE
.ChartTitle.AutoScaleFont = False
With .ChartTitle.Font
.Name = "Calibri"
.FontStyle = "Bold"
.Size = 14
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.ColorIndex = xlAutomatic
.Background = xlAutomatic
End With
'AXIS STYLE-----------------------------------------------------------------------
.Axes(xlCategory).TickLabels.AutoScaleFont = False
With .Axes(xlCategory).TickLabels.Font
.Name = "Arial"
.FontStyle = "Regular"
.Size = 10
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.ColorIndex = xlAutomatic
.Background = xlAutomatic
With Selection.Border
.ColorIndex = 15
.LineStyle = xlContinuous
End With
End With
.Axes(xlValue).TickLabels.AutoScaleFont = False
With .Axes(xlValue).TickLabels.Font
.Name = "Calibri"
.FontStyle = "Regular"
.Size = 8
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.ColorIndex = xlAutomatic
.Background = xlAutomatic
End With
End With
'-----------------------------------------------------------------------------
' HEIGHT; WIDTH AND POSITION
GraphLocation = CSD.Cells(Rows.Count, 2).End(xlUp).Row + 3
Dim RngToCover As Range
Set RngToCover = ActiveSheet.Range(Cells(GraphLocation, 2), Cells(GraphLocation + 20, 11))
With ActiveChart.Parent
.Height = RngToCover.Height ' resize
.Width = RngToCover.Width ' resize
.Top = RngToCover.Top ' reposition
.Left = RngToCover.Left ' reposition
End With
' for each row in the sheet
For i = FirstRow To LastRow
Dim chartName As String
' define chart data range for the row (record)
Set rngChtData = WSD.Range(WSD.Cells(i, FirstColumn), WSD.Cells(i, LastColumn))
'To get the serie name that I´m going to add to the graph
Dim serieName As String
Dim varItemName As Variant
WSD.Activate
varItemName = WSD.Range(Cells(i, 1), Cells(i, 4))
serieName = CStr(varItemName(1, 1) + " " + varItemName(1, 2) + " " + varItemName(1, 3) + " " + varItemName(1, 4))
' add series from selected range, column by column
CSD.ChartObjects.Select
With ActiveChart
With .SeriesCollection.NewSeries
.Values = rngChtData
.XValues = rngChtXVal
.Name = serieName
End With
End With
Next i
'We let as last view the page with all the info
CSD.Select
End Sub
I am calling this Sub from other one. The next step will be calling a similar method (exactly the same but other starting point to get the data and some different format properties)for other kind of table and graphic:
Public Sub printGraphics()
Modul4.ClearGraphs
Modul4.generateGraphicsC (RowResistiveC)
Modul4.generateGraphicsT (RowResistiveT)
End Sub
And so on. CountXelements and Yelements counts the number of elements from the Tables Sheet and RowResistiveC, for example, keeps the position of the table.
GenerateGraphicsC works but generateGraphicsT (exactly the same) crush in the line:
With .SeriesCollection.NewSeries
Whit error 91 ( I have a german version of excel at work but it's something like variable object or bloque object not given).
As I suspected the error came from :
CSD.ChartObjects.Select
That works in my solution for the first graph since I'm selecting the single graphic on the sheet, but when I add more it doesn´t.
I just changed that line for:
CSD.ChartObjects(1).Activate
and so on. It works perfectly. I also had to make some adjusments to avoid all the graphs being plotted over the previous one, but it works nice.
Related
I have a worksheet with 300 columns and would like to create one scatter plot for each column, bringing data from two other sheets that are in the same worksheet.
The problem is that I´m not familiar with VBA, and some error codes don't help at all.
Private Sub Create_Charts()
Dim sh As Worksheet
Dim chrt As Chart
For i = 1 To 300
Set sh = ActiveWorkbook.Worksheets("Graphs")
Set chrt = sh.Shapes.AddChart.Chart
With chrt
'Data
.ChartType = xlXYScatter
.SeriesCollection.NewSeries
.SeriesCollection(1).Name = "=""Scatter Chart"""
'With the following parameters it works:
'.SeriesCollection(1).XValues = "=OP!$c$4:$c$1588"
'.SeriesCollection(1).Values = "=PV!$c$4:$c$1588"
'But I need something like this:
.SeriesCollection(1).XValues = CStr(Worksheets("PV").Range(Cells(i, 4), Cells(i, 1588)))
.SeriesCollection(1).Values = CStr(Worksheets("OV").Range(Cells(i, 4), Cells(i, 1588)))
'Location
.ChartArea.Left = 380 * i - 380
.ChartArea.Top = 100
.ChartArea.Height = 360
.ChartArea.Width = 360
'Formatting
.Axes(xlCategory).HasMajorGridlines = True
.Axes(xlValue).HasMajorGridlines = True
.HasAxis(xlCategory, xlPrimary) = False
.HasAxis(xlValue, xlPrimary) = False
.HasLegend = False
End With
Next i
End Sub
This line references a column:
.SeriesCollection(1).XValues = "=OP!$c$4:$c$1588"
This references a row, row i from column 4 to column 1588:
.SeriesCollection(1).XValues = CStr(Worksheets("PV").Range(Cells(i, 4), Cells(i, 1588)))
But you also need to reference not only Range but Cells. And if you pass in a string address, you need the leading "="; it's easier to pass in a range. So try this:
Dim wsPV As Worksheet, wsOV As Worksheet
Dim rngX As Range, rngY As Range
Set wsPV = ActiveWorkbook.Worksheets("PV")
Set wsOV = ActiveWorkbook.Worksheets("OV")
Set rngX = wsPV.Range(wsPV.Cells(4, i), wsPV.Cells(1588, i)
Set rngY = wsOV.Range(wsOV.Cells(4, i), wsOV.Cells(1588, i)
chrt.SeriesCollection(1).XValues = rngX
chrt.SeriesCollection(1).Values = rngY
So I am trying to format a XY scatter chart in Excel using VBA and I would like to have lines connecting the markers, but for both the markers and the marker lines I would like for them to be invisible.
For some reason both the marker line and the line that connects the markers both use the same code to change their visibility property.
chart.SeriesCollection(1).Format.Line.Visible = msoFalse
I can change the colours independently using the MarkerBackGroundColor property, but I can't seem to figure out how to make one visible without making the other visible as well.
Any help on this would be very much appreciated.
You can use
FullSeriesCollection(1).Border.LineStyle = xlNone
or
FullSeriesCollection(1).Border.LineStyle = xlSolid
to format the line only.
The code seems to set point. Bellow code is sample of setting points.
Sub ScatterChart_setPoint()
Dim Ws As Worksheet
Dim DB As Range, myCell As Range
Dim Ch As Chart
Dim i As Integer, n As Long, r As Integer, g As Integer, b As Integer
Dim vX(), vY(), vLable(), vMarker
Dim pnt As Point
Dim Shp As Shape
Dim h As Single, w As Single, l As Single, t As Single, fs As Single
Application.DisplayAlerts = False
Set Ws = ActiveSheet 'Sheets("Current Account")
Ws.Activate
Ws.Range("a65536").Select
vMarker = Array(xlMarkerStyleCircle, xlMarkerStyleDash, xlMarkerStyleDiamond, xlMarkerStyleDot, _
xlMarkerStylePlus, xlMarkerStyleSquare, xlMarkerStyleStar, _
xlMarkerStyleTriangle, xlMarkerStyleX)
Set DB = Ws.Range("h3", Ws.Range("h3").End(xlDown)) '<~~ range of data
For Each myCell In DB
If myCell = 0 Or myCell.Offset(, 10) = "" Then
Else
n = n + 1
ReDim Preserve vX(1 To n)
ReDim Preserve vY(1 To n)
ReDim Preserve vLable(1 To n)
vX(n) = myCell
vY(n) = myCell.Offset(, 10)
vLable(n) = myCell.Offset(, -7)
End If
Next myCell
Charts.Add
With ActiveChart
.HasTitle = True
.ChartType = xlXYScatter
.Legend.Position = xlLegendPositionRight
With .ChartTitle
.Characters.Text = Ws.Range("a1").Value
.Characters.Font.Size = 12
End With
.SeriesCollection.NewSeries
With .SeriesCollection(1)
.Name = "OECD"
.XValues = vX
.Values = vY
.Trendlines.Add
With .Trendlines(1)
.DisplayRSquared = True
.DisplayEquation = True
End With
End With
.Axes(xlValue, xlPrimary).HasTitle = True
.Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = Ws.Range("r2")
.Axes(xlCategory, xlPrimary).HasTitle = True
.Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = Ws.Range("h2")
For i = 1 To n
Set pnt = .SeriesCollection(1).Points(i)
With pnt
.ApplyDataLabels
.DataLabel.Text = vLable(i)
.DataLabel.ShowValue = False
.DataLabel.ShowCategoryName = True
.MarkerStyle = vMarker(WorksheetFunction.RandBetween(0, 8))
With WorksheetFunction
r = .RandBetween(0, 240)
g = .RandBetween(0, 240)
b = .RandBetween(0, 240)
End With
.MarkerForegroundColor = RGB(r, g, b)
.MarkerBackgroundColor = RGB(r, g, b)
End With
.ApplyDataLabels
Next i
Application.DisplayAlerts = True
End Sub
I am extremely new to excel vba and am using this first attempt as a learning experience. I am hoping to make a matrix of scatterplots in a separate sheet from the sheet they are taking the data from.
So heres a kind of schematic of the graphs I would like to be generated in an excel sheet. This represents a single satterplot [x-axis(ColumnletterRownumber), y-axis(ColumnletterRownumber)]
[(S2:S372),(AW2:AW372)] [(T2:T372),(AW2:AW372)] [(U2:U372),(AW2:AW372)]
[(S2:S372),(AX2:AX372)] [(T2:T372),(AX2:AX372)] [(U2:U372),(AX2:AX372)]
[(S2:S372),(AY2:AY372)] [(T2:T372),(AY2:AY372)] [(U2:U372),(AY2:AY372)]
[(S2:S372),(AZ2:AZ372)] [(T2:T372),(AZ2:AZ372)] [(U2:U372),(AZ2:AZ372)]
So those would be the scatterplots on the next sheet. Obviously I need a lot more graphs than that but that should give you an idea.
Here's what I got so far:
Sorry in advance for the large amount of commented out things... those are ideas I think might help but I haven't gotten them to work.
Sub SPlotMatrix1()
Application.ScreenUpdating = False
'SPlotMatrix1 Macro
'Define the Variables
'---------------------
Dim Xaxis As range
Dim Yaxis As range
''Initialize the Variables
''-------------------------
Set Xaxis = range("S2:S372")
Set Yaxis = range("AW2:AW372")
'Tell macro when to stop
'-----------------------
Dim spot As Long
spot = 0
Do Until spot > 50
Sheets("2ndFDAInterimData").Select
''MAIN LOOP
'Graph1
'-------
'Selection Range
range("S2:S372,AW2:AW372").Select
'range("Xaxis,Yaxis").Select
'range("AW1:AW372",S1:S372").Offset(0, rng).Select
'range("AW1:AW372", 0).Select
'range("0,S1:S372").Offset(0, rng).Select
range("S372").Activate
'Select Graph Range
ActiveSheet.Shapes.AddChart2(240, xlXYScatter).Select
' ActiveChart.SetSourceData Source:=range( _
"'2ndFDAInterimData'!$AW$1:$AW$372,'2ndFDAInterimData'!$S$1:$S$372")
'Graph Title
ActiveChart.SetElement (msoElementChartTitleAboveChart)
ActiveChart.FullSeriesCollection(1).Select
ActiveChart.FullSeriesCollection(1).name = "='2ndFDAInterimData'!$DL$1"
'Add Trendline
ActiveChart.Axes(xlValue).MajorGridlines.Select
ActiveChart.FullSeriesCollection(1).Trendlines.Add Type:=xlLinear, Forward _
:=0, Backward:=0, DisplayEquation:=0, DisplayRSquared:=0, name:= _
"Linear (Ave.Score)"
ActiveChart.FullSeriesCollection(1).Trendlines.Add Type:=xlLinear, Forward _
:=0, Backward:=0, DisplayEquation:=0, DisplayRSquared:=0, name:= _
"Linear (Ave.Score)"
ActiveChart.FullSeriesCollection(1).Trendlines(2).Select
Selection.DisplayRSquared = True
'Move Rsquare Label to Corner
ActiveChart.FullSeriesCollection(1).Trendlines(2).DataLabel.Select
Selection.Left = 30.114
Selection.Top = 13.546
'Format Trendline
ActiveChart.FullSeriesCollection(1).Trendlines(2).Select
With Selection.Format.Line
.Visible = msoTrue
.ForeColor.ObjectThemeColor = msoThemeColorText1
.ForeColor.TintAndShade = 0
.ForeColor.Brightness = 0
.Transparency = 0
End With
With Selection.Format.Line
.Visible = msoTrue
.DashStyle = msoLineSolid
End With
ActiveChart.ChartArea.Select
With Selection.Format.Line
.Visible = msoTrue
.Weight = 1.75
End With
'Resize Graph
ActiveChart.Parent.Height = 180
ActiveChart.Parent.Width = 239.76
'Y axis scale
ActiveChart.FullSeriesCollection(1).Select
ActiveChart.Axes(xlValue).Select
ActiveChart.Axes(xlValue).MaximumScale = 100
'Move graph to center (for the purposes of design and debugging)
ActiveChart.Parent.Cut
range("V4").Offset(spot, 0).Select
ActiveSheet.Paste
' 'Move Graph to other sheet
' ActiveChart.Parent.Cut
' Sheets("graphs").Select
' range("A1").Offset(spot, 0).Select
' ActiveSheet.Paste
spot = spot + 14
Loop
Application.ScreenUpdating = True
End Sub
I've gotten to the point where I am creating a number of the same graphs in a row or column if I want. But I can't successfully get the graphs ranges to change so that they are plotting different data.
Please help, let me know if I can further clarify. Thank you!
You can define the data with a couple simple loops. Create the chart and embellish it within the inner loop.
Sub InsertMultipleCharts()
' data particulars
Dim wksData As Worksheet
Const Xcol1 As Long = 19 ' column S
Const Xcol2 As Long = 21 ' column U
Const Ycol1 As Long = 49 ' column AW
Const Ycol2 As Long = 52 ' column AZ
Const Row1 As Long = 2
Const Row2 As Long = 372
' chart dimensions
Const FirstChartLeft As Long = 50
Const FirstChartTop As Long = 50
Const ChartHeight As Long = 180
Const ChartWidth As Long = 240
' working variables
Dim wksChart As Worksheet
Dim cht As Chart
Dim Xrange As Range
Dim Yrange As Range
Dim Xcol As Long
Dim Ycol As Long
' define sheets
Set wksData = ActiveSheet
Set wksChart = Worksheets.Add
' loop X
For Xcol = Xcol1 To Xcol2
' define x values
Set Xrange = Range(wksData.Cells(Row1, Xcol), wksData.Cells(Row2, Xcol))
' loop Y
For Ycol = Ycol1 To Ycol2
' define y values
Set Yrange = Range(wksData.Cells(Row1, Ycol), wksData.Cells(Row2, Ycol))
' insert chart
Set cht = wksChart.Shapes.AddChart2(Style:=240, XlChartType:=xlXYScatter, _
Left:=FirstChartLeft + (Xcol - Xcol1) * ChartWidth, _
Top:=FirstChartTop + (Ycol - Ycol1) * ChartHeight, _
Width:=ChartWidth, Height:=ChartHeight).Chart
' assign data to chart
cht.SetSourceData Source:=Union(Xrange, Yrange)
' chart title
cht.HasTitle = True
With cht.ChartTitle.Font
.Size = 12
.Bold = False
End With
' axis scale
cht.Axes(xlValue).MaximumScale = 100
' legend
cht.HasLegend = False
' series: name, trendline, and Rsquared
With cht.SeriesCollection(1)
.Name = "Series Name" '''' don't know where these are coming from
With .Trendlines.Add(Type:=xlLinear, DisplayRSquared:=True).DataLabel
.Format.Line.DashStyle = msoLineSolid
.Top = cht.PlotArea.InsideTop
.Left = cht.PlotArea.InsideLeft
End With
End With
Next
Next
End Sub
Macro recorder code is messy, but it gives you syntax.
Try using the macro recorder to edit an existing range so you get the code for setting the ranges for X, Y and the range name and size.
Once recorded you can swap out the new ranges as variables to get the new charts.
Firstly I created 4 pivot tables into 1 worksheet named OOTWeeklyTrendperPlatform, OOTWeeklyTrendperFailureMode, OverallWeeklyTrendperDereel, OverallWeeklyTrendperEngDataValue. These portion was completed successfully.
After that from each of these 4 pivot tables I wanted to create pivot chart. So there is 4 pivot tables and 4 pivot charts inside 1 worksheet.
My sequence of work is this way (table and chart name is for illustration purpose) table1 then chart1 then table2 then chart2 and so on. The problem is that after completed table1, chart1, and table2; I get an error when producing chart2 (or second chart correspond to table2). Please find shortened code below.
Sub MakePivotTableDereel()
Dim PTCache As PivotCache, PTCache1 As PivotCache
Dim PT As PivotTable, PT1 As PivotTable, PT2 As PivotTable, PT3 As PivotTable
Dim rngChart As Range, rngChart1 As Range, rngChart2 As Range, rngChart3 As Range
Dim objChart As ChartObject, objChart1 As ChartObject, objChart2 As ChartObject, objChart3 As ChartObject
Dim PivotDereel As Worksheet
Application.ScreenUpdating = False
' Delete PivotSheet if it exists
On Error Resume Next
Application.DisplayAlerts = False
Sheets("PivotDereel").Delete
On Error GoTo 0
' Create Pivot Cache
Set PTCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=Sheets("Data").Range("A1").CurrentRegion.Address)
' Add PivotDereel sheet
Set PivotDereel = Worksheets.Add
ActiveSheet.Name = "PivotDereel"
Cells(1, 1).Value = "OOT Weekly Trend per Platform"
Cells(1, 1).Font.Size = 16
Cells(1, 15).Value = "OOT Weekly Trend per Failure Mode"
Cells(1, 15).Font.Size = 16
Cells(1, 29).Value = "Overall Weekly Trend per Dereel"
Cells(1, 29).Font.Size = 16
Cells(1, 39).Value = "Overall Weekly Trend per Eng Data Value"
Cells(1, 39).Font.Size = 16
' Create pivot table OOTWeeklyTrendperPlatform
Set PT = ActiveSheet.PivotTables.Add(PivotCache:=PTCache, TableDestination:=PivotDereel.Cells(4, 1), TableName:="OOTWeeklyTrendperPlatform")
' set table properties below
With PT
.PivotFields("Work Week").Orientation = xlRowField
.PivotFields("PLATFORM").Orientation = xlColumnField
.PivotFields("EngDataValue").Orientation = xlPageField
.PivotFields("LotID").Orientation = xlDataField
.DisplayFieldCaptions = False
.TableStyle2 = "PivotStyleMedium2"
.PivotFields("Count of LotID").Caption = "Lot ID"
End With
' Filter unwanted data below
PT.PivotFields("EngDataValue").CurrentPage = "(All)"
With PT.PivotFields("EngDataValue")
.PivotItems("BROKEN SEAL").Visible = False
'.PivotItems("DAMAGED MATERIAL").Visible = False
.PivotItems("COGHOLE DAMAGE").Visible = False
'.PivotItems("DEBRIS IN TAPE").Visible = False
.PivotItems("DRIFTED COVER TAPE").Visible = False
'.PivotItems("DROPPED REEL").Visible = False
.PivotItems("EMPTY POCKET").Visible = False
'.PivotItems("ENGINEERING REQUEST").Visible = False
.PivotItems("LOOSE COVER TAPE").Visible = False
.PivotItems("MACHINE COUNT ERROR").Visible = False
.PivotItems("MACHINE LOCKED UP").Visible = False
.PivotItems("OUT OF MATERIALS").Visible = False
.PivotItems("OUT OF PURGE TIME").Visible = False
'.PivotItems("OVER/UNDER SEALED").Visible = False
.PivotItems("PART OUT OF POCKET").Visible = False
'.PivotItems("PO ERROR").Visible = False
.PivotItems("TECH PURGED SYSTEM").Visible = False
.PivotItems("THICK/THIN SEAL").Visible = False
End With
PT.PivotFields("EngDataValue").EnableMultiplePageItems = True
' Create pivot chart OOTWeeklyTrendperPlatform
Debug.Print PT.TableRange2.Columns.Count
'Use the ChartObjects.Add Method to add an embedded Pivot Chart, which is represented as a ChartObject object. Note that the arguments Left and Width are mandatory to specify in this method. This method allows you to set the position and size (both in points) of the chart.
Set objChart = Sheets("PivotDereel").ChartObjects.Add(Left:=10, Top:=25 * (PT.TableRange2.Rows.Count), Width:=300, Height:=200)
'set data source range for the Chart:
Set rngChart = PT.TableRange2
With objChart.Chart
.SetSourceData Source:=rngChart
End With
With objChart.Chart
.HasTitle = True
.ChartTitle.Characters.Text = "OOT Weekly Trend per Platform"
.ChartTitle.Font.Bold = True
.ChartTitle.Font.Size = 14
End With
' Create pivot table OOTWeeklyTrendperFailureMode
Set PT1 = ActiveSheet.PivotTables.Add(PivotCache:=PTCache, TableDestination:=PivotDereel.Cells(4, 15), TableName:="OOTWeeklyTrendperFailureMode")
With PT1
.PivotFields("Work Week").Orientation = xlRowField
.PivotFields("Failure Mode").Orientation = xlColumnField
.PivotFields("EngDataValue").Orientation = xlPageField
.PivotFields("LotID").Orientation = xlDataField
.DisplayFieldCaptions = False
.TableStyle2 = "PivotStyleMedium2"
.PivotFields("Count of LotID").Caption = "Lot ID"
End With
PT1.PivotFields("EngDataValue").CurrentPage = "(All)"
With PT1.PivotFields("EngDataValue")
.PivotItems("BROKEN SEAL").Visible = False
'.PivotItems("DAMAGED MATERIAL").Visible = False
.PivotItems("COGHOLE DAMAGE").Visible = False
'.PivotItems("DEBRIS IN TAPE").Visible = False
.PivotItems("DRIFTED COVER TAPE").Visible = False
'.PivotItems("DROPPED REEL").Visible = False
.PivotItems("EMPTY POCKET").Visible = False
'.PivotItems("ENGINEERING REQUEST").Visible = False
.PivotItems("LOOSE COVER TAPE").Visible = False
.PivotItems("MACHINE COUNT ERROR").Visible = False
.PivotItems("MACHINE LOCKED UP").Visible = False
.PivotItems("OUT OF MATERIALS").Visible = False
.PivotItems("OUT OF PURGE TIME").Visible = False
'.PivotItems("OVER/UNDER SEALED").Visible = False
.PivotItems("PART OUT OF POCKET").Visible = False
'.PivotItems("PO ERROR").Visible = False
.PivotItems("TECH PURGED SYSTEM").Visible = False
.PivotItems("THICK/THIN SEAL").Visible = False
End With
PT1.PivotFields("EngDataValue").EnableMultiplePageItems = True
' Create pivot chart OOTWeeklyTrendperFailureMode
'Use the ChartObjects.Add Method to add an embedded Pivot Chart, which is represented as a ChartObject object. Note that the arguments Left and Width are mandatory to specify in this method. This method allows you to set the position and size (both in points) of the chart.
Set objChart1 = Sheets("PivotDereel").ChartObjects.Add(Left:=10, Top:=25 * (PT1.TableRange2.Rows.Count), Width:=300, Height:=200)
'set data source range for the Chart:
Set rngChart1 = PT1.TableRange2
With objChart1.Chart
.SetSourceData Source:=rngChart1
End With
With objChart.Chart
.HasTitle = True
.ChartTitle.Characters.Text = "OOT Weekly Trend per Platform"
.ChartTitle.Font.Bold = True
.ChartTitle.Font.Size = 14
End With
'below is the portion to create 3rd and 4th pivot tables and charts
end sub
I get error: Method 'SetSourceData' of object '_chart' failed at part,
With objChart1.Chart
.SetSourceData Source:=rngChart1
End With
This part suppose to assign source data for the second chart. But it fails. Do you have the solution?
If any cell in a pivot table is selected, a chart that you insert will automatically use the whole pivot table as its source data. I just ran this on a worksheet with a handful of pivot tables:
for i=1 to 4
activesheet.pivottables(i).tablerange2.cells(1,1).select
ActiveSheet.Shapes.AddChart
' here you need to specify chart type and style, size and position, etc.
next
No need for SetSourceData (which gave me unexpected problems before I simplified as above).
I wrote the following code to add a chart and position it on a worksheet with data on it:
Dim sh As Worksheet
Dim chrteit As Chart
lastrows = Range("A2").End(xlDown).Row
Set sh = ActiveWorkbook.Worksheets("TraceTable")
Set chrteit = sh.Shapes.AddChart.Chart
With chrteit
.ChartType = xlXYScatter
.SeriesCollection.NewSeries
.SeriesCollection(1).XValues = sh.Range(Cells(2, 6), Cells(lastrows, 6))
.SeriesCollection(1).Values = sh.Range(Cells(2, 7), Cells(lastrows, 7))
.HasTitle = True
.ChartTitle.Text = "EIT"
.Parent.Height = Range("N2:N14").Height
.Parent.Width = Range("N2:T2").Width
.Parent.top = Range("N2").top
.Parent.Left = Range("N2").Left
End With
The problem is, later in my module I have a macro that will an entire row between two data points if the two data points are different, and it is as follows:
Private Sub Dividers()
Dim DividerRange As Range, lastrow As Long, k As Integer, counter As Integer
lastrow = Range("C2").End(xlDown).Row
Set DividerRange = Range(Cells(2, 3), Cells(lastrow, 3))
counter = 0
For k = 2 To DividerRange.Count
If DividerRange(k + counter).Value <> DividerRange(k + counter - 1).Value Then
DividerRange(k + counter).EntireRow.Insert
counter = counter + 1
Else
End If
Next k
End Sub
By adding the entire row, it changes the height of my graph and it's position. I want it to be a fixed position, how can I do this? I would PREFER not to change the second code, but rather the first but let me know any solutions you guys have, Thanks!
Add this line to the first procedure:
chrteit.Placement = xlFreeFloating
This is the same as right-click, format chart area, properties: Don't move or size with cells.
|
Or you could place that method inside the With block, thusly:
With chrteit
.ChartType = xlXYScatter
.SeriesCollection.NewSeries
.SeriesCollection(1).XValues = sh.Range(Cells(2, 6), Cells(lastrows, 6))
.SeriesCollection(1).Values = sh.Range(Cells(2, 7), Cells(lastrows, 7))
.HasTitle = True
.ChartTitle.Text = "EIT"
.Parent.Height = Range("N2:N14").Height
.Parent.Width = Range("N2:T2").Width
.Parent.top = Range("N2").top
.Parent.Left = Range("N2").Left
.Placement = xlFreeFloating
End With