Excel VBA Chart Generation - excel

I'm fairly new to VBA and I'm trying to implement a certain type of graph based off of the following example data: https://docs.google.com/spreadsheet/pub?key=0AjZu7FPYRXsjdEJMLTN2MTZhUldpNnhYeW0wNF8taFE&output=html
I've attempted using the macro recorder but I haven't had any luck getting it to work as required.
I'd like to have a ScatterPlot with lines and Markers with the X-Values of the chart equal to the dates presented, the left Y axis be a range from 0 to 4 (with the steps inbetween equal to 1) and I'd also like to have a second y-axis where the max is the max number presented in the data (so in this case 45). Also, is there any way to name the series other than 'Series1', 'Series2' etc.?
In the end I'll cut down the number of series (probably a max of six).
Anyways any help would be greatly appreciated!
Edit: Here is the code provided by the macro recorder:
ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlXYScatterLines
ActiveChart.SetSourceData Source:=Range("TimelineGenerator!$C$1:$W$11")
ActiveChart.Axes(xlValue).Select
ActiveChart.Axes(xlValue).MaximumScale = 4
ActiveChart.Axes(xlValue).MinimumScale = 0
ActiveChart.Axes(xlValue).MajorUnit = 1
But when I execute this to generate my graph via vba, it has the dates as series instead of the xValues of the chart.

Related

Need VBA code to plot up series of linear data in Excel, create regression eq's for each series, then write the regression eq's in the Excel sheet

I have a fairly simple VBA code which is doing 75% of what I need it to do, I just can't get the last step to work properly.
In an Excel sheet, I have two sets of data (X data and Y data). The x data is the same two data values for every single case. Then I have two columns of data which comprise the Y data. I need to create an Excel scatter plot with a whole bunch of data series. Series 1 is the two constant x values with the first y value from the first column and the first y value from the second column. The 2nd series is the same two constant x values with the second y value from the first column and the second y value from the second column, and so on. The columns have about 300+ rows (hence > 300 series total). I realize that a scatter plot can only do up to about 256 series in one plot so I won't be able to fit them all in one plot. That's not the point. I've tried just plotting like, say, 50 of the series and I have that part working fine. Next, because all the series are straight lines, I need the slope/regression information from each series, so I create a linear trendline and plot the equation on the chart. I have this part automated and working correctly in Excel as well. Here's where I'm stuck though. The last step is, after I've had VBA create the, say, 50 series in the single plot and generate all of the regression equations, I then need for Excel to take those equations and paste them into a column in the main worksheet (where the plotting data resides). I found something on Google that is supposed to do this (grabbing trendline.datalabel.text and pasting it into the sheet), but it isn't working right, and I can't figure out what I'm doing wrong. I've tried 20 different things and am still beating my head against a wall. Any help with the last half of the code would be greatly appreciated. THANK YOU.
Sub Plot_slopes()
Dim i As Integer
Dim ChtOb As ChartObject
Dim objTrendline As Trendline
Dim strEquation As String
Set ChtOb = ActiveSheet.ChartObjects.Add(Left:=20, Width:=800, Top:=20, Height:=250)
ChtOb.Chart.ChartType = xlXYScatterSmoothNoMarkers
ChtOb.Activate
i = 9
For i = 9 To 59
With ActiveChart.SeriesCollection.NewSeries
.Name = "FS" & i
.XValues = Worksheets("summary").Range(Worksheets("summary").Cells(3, 7), Worksheets("summary").Cells(4, 7))
.Values = Worksheets("summary").Range(Worksheets("summary").Cells(i, 13), Worksheets("summary").Cells(i, 14))
.Trendlines.Add
End With
With ActiveSheet.ChartObjects(1).Chart
Set objTrendline = .Trendlines(1)
With objTrendline
.DisplayRSquared = False
Trendlines(1).DisplayEquation = True
strEquation = .DataLabel.Text
Range("Q9").Offset(i, 0) = strEquation
End With
End With
Next i
End Sub
I mainly need help with the code after the first With Block and where it starts with a new "with"..."with activesheet.chartobjects(1).chart", etc), although, I'm also having trouble with the .name part in the first With block as well. Goal is to get the last block so that VBA writes out the regression equations for each created series into the main "summary" worksheet

Various transparent step in a line in a chart

I am using VBA with Excel 2013. I am developing a Macro with a chart, inside the chart there is a line made with a serie if points. I need apply a transparency shape to the steps between 2 point.
example
1 to 2 solid
2 to 3 transparent
3 to 4 solid
With .transparency = 0 and 1 the shape is applied to the whole line. I tryed to apply .trasnparency various time but it is applied to the whole line.
How do I apply transparency to have the behauvior described above?
The easiest way to get a gap is to insert a blank row between segments you want to be visible. In the top view below the data range is continuous, and so is the chart. In the bottom view, I've inserted blank rows between the X-Y values for the horizontal segments, and the chart rewards me with gaps in the plot, so the verticals don't show up.
You can't get these gaps if your code is inserting arrays into the chart series source data, but you can use code like this to make them disappear (by using No Line instead of Transparency, personal preference):
Sub TransparentVerticals()
Dim srs As Series
Dim iPt As Long
Set srs = ActiveChart.SeriesCollection(1)
For iPt = 1 To srs.Points.Count Step 2
With srs.Points(iPt)
.Format.Line.Visible = msoFalse
End With
Next
End Sub

excel macros - line chart loses year axis values and chart title

I am recording a macro using Excel 2013 to create a line chart.
I have one column with years and an adjacent column with population values. The column headings are "Year" and "Population" respectively.
The line chart looks good.
When I run the macro, the chart title (Population) is striped out. Additionally the year values (x axis) are replaced with a number series, 1 . . . onwards
How do I have the macro retain the year values and the chart title (Population)?
Thanks!
This is my recorded Macro
Range("A1:B29").Select
ActiveWindow.WindowState = xlMaximized
ActiveSheet.Shapes.AddChart2(227, xlLineMarkers).Select
ActiveChart.SetSourceData Source:=Range("compilation!$A$1:$B$29")
This is an example of what I want the final graph to look like when I run the macro.
Add the following line to your last line of your macro
ActiveChart.FullSeriesCollection(1).XValues = "=compilation!$A$2:$A$29"
That should get you your year back along the bottom.
ActiveChart.SetElement (msoElementChartTitleAboveChart)
ActiveChart.ChartTitle.Select
Selection.Caption = "=compilation!R1C2"
That will set your Title for you. However you still need your Primary Horizontal Title so why dont we throw in this tid bit of random code:
ActiveChart.Axes(xlCategory).Select
ActiveChart.SetElement (msoElementPrimaryCategoryAxisTitleAdjacentToAxis)
Selection.Caption = "=compilation!R1C1"
now the only outstanding issue is if you are generating 1 or 2 lines in your graph.
To get rid of the second line (technically the first since its really series 1) we have two choices.
Choice 1 is to select it with the code and delete it. I am going to opt for choice 2 though. Choice 2 is to never add it in the first place!
So to start with eliminate your first line of your Macro. When the graph is initially created, it will be created as a blank slate as there is no preselected data. So what we need to do is change 1 lettre in the line of your macro where you define the Source. (4th line of your posted code) and we are going to change the starting cell reference from $A$1 to $B$1. If the graph only has one column of data to work with for points then there can only be one series. So that line will look like the following in the end:
ActiveChart.SetSourceData Source:=Range("compilation!$B$1:$B$29")

Change orientation of chart and legend using excel VBA

For some reason if there is less than four rows of data and you try and scatter chart it the cluster (column A) is shown on the legend, but if more than 4 rows of data exist then the other columns (A, B, C) are on the legend (Y axis).
Can you please show me using VBA how do I re orientate this graph to look like graph (2)?
I need to reorient the legend series to be on the horizontal category axis using VBA(since the macro recorder doesn't show how to do this.
GRAPH 1 STARTS OFF LOOKING LIKE THIS
GRAPH 2 THIS IS HOW I DO IT MANUALLY
(reorient legend entries - left, and category labels - right)
GRAPH 3 The scatterchart dialog ends up looking like this, which is what I want to do in VBA
GRAPH 4 Final Graph looks like this, This is what I want to achieve in VBA
Lastly this is what the macro recorder creates, but when I try and run it, its missing, the range and Plotby parameters and fails
Range("A1:D3").Select
Range("D3").Activate
ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlXYScatter
ActiveChart.SetSourceData
Your columns and rows are reversed. When you have the chart selected go und "Design" contextual tab and click "Switch Row/Column". Does that fix it? If yes you can use:
ActiveChart.PlotBy = xlRows or ActiveChart.PlotBy = xlColumns
to do it programatically.

VBA Pie Chart Legend - How to set legend text?

A similar question was asked (Set Legend Text Pie Chart) but the solution doesn't work for me, maybe I'm missing something. I'm fairly new to working with VBA/Excel/Access and reports and I'm on a limited deadline so I am hoping somebody can enlighten me.
What I am doing is populating a range of cells with values pulled from an access database and then programatically generating pie charts based on these cell values. The pie charts are fairly simple and contain 2 pieces of data. I am generating 1-4 of them based on the users' selections. So for example, the user can choose A, B, C And/Or D and each letter corresponds to 2 cell columns that contain # of Correct & # of Incorrect for each chart
The reports are being generated inside of a loop (1 to 4) corresponding to A/B/C/D
The Code I'm using to create the charts looks like this:
Charts.Add
ActiveChart.ChartType = xlPie
ActiveChart.SetSourceData Source:=Sheets("Sheet1").Range(Cells(20,shift(shiftIndex)), Cells(21, shift(shiftIndex))
ActiveChart.HasLegend = True
Which is saying to use the range B20:B21, C20:C21, etc for the Correct/Incorrect values. The problem is that the legend is showing "1" & "2" as labels and I want it to show "Correct" & "Incorrect"
In the other question, the person suggested using the syntax:
ActiveChart.SetSourceData Source:=Sheets("Sheet1").Range("b6:c6," & "b" & x & ":c" & x)
Where b6 would contain "Correct" and c6 would contain "Incorrect" in my case for my labels but when I use this:
ActiveChart.SetSourceData Source:=Sheets("Sheet 1").Range("a26:a27, a20:a21")
Where a26 contains "Correct", a27 contains "Incorrect" and a20 & a21 contain my correct and incorrect values - it tries to use all 4 values in my pie chart. Am I missing something here? Separating the parameters by a comma should indicate the first range as my legend and the second as my data source?
you can directly control this using the XValues property of the Series object...
Assuming you have only one series in the chart try:
Activechart.Seriescollection(1).XValues=Activesheet.Range("a26:a27")
a further tip would be to do this:
Dim chMyChart as Chart
Dim chMySeries as Series
Set chMyChart = Activesheet.Activechart
Set chMySeries = chMyChart.Seriescollection(1)
and then use chMyChart in place of Active chart and chMySeries in place of ActiveChart etc.
This is more efficient, but it also activates vba's Intellisense that shows you a list of all of the properties available for these objects after you enter the ".".
For me anyway, this doesn't seem to be exposed on objects like Active??? or indexed objects like chMyChart.SeriesCollection(1)

Resources