How to set a series names in code generated chart - excel

Good morning.
I created a VB.NET application for Energy Measurement. All is OK, only one thing is a problem. In app, is code to create an excel table and also a chart. Table and chart are generated right, but series names in the chart are with default series names (e.g.: Series1, Series2... etc.). Only the last series has the right name what I set in code (I set all, but they are changed).
My code for the chart is:
Private Sub AddChart(Row As Integer, Columns As Integer)
xlWorkSheet = xlWorkBook.Sheets(2)
xlCharts = xlWorkSheet.ChartObjects
myChart = xlCharts.Add(0, 0, 1000, 500)
EnergyChart = myChart.Chart
xlWorkSheet = xlWorkBook.Sheets(1)
For i As Integer = 1 To Columns - 1
ColValue = ConvertNumberToString(i + 1)
SeriesName(i) = xlWorkSheet.Range(ColValue & "3").Value
chartRange = xlWorkSheet.Range("A4", ColValue & Row - 1)
EnergyChart.SetSourceData(Source:=chartRange)
Series = CType(EnergyChart.SeriesCollection(i), Excel.Series)
Series.Name = SeriesName(i)
Next
With EnergyChart
.HasTitle = True
.ChartTitle.Font.Color = Color.SeaGreen
.ChartTitle.Font.Size = 11
.ChartTitle.Font.Name = "Calibri"
.ChartTitle.Text = ReportFileName
.ChartType = Excel.XlChartType.xlLine
End With
End Sub
Could you please someone tell me why series names are changed to default? Thank you all.
SOLVED:
After code modification it's working right.
Private Sub AddChart(Row As Integer, Columns As Integer)
xlWorkSheet = xlWorkBook.Sheets(2)
xlCharts = xlWorkSheet.ChartObjects
myChart = xlCharts.Add(0, 0, 1000, 500)
EnergyChart = myChart.Chart
xlWorkSheet = xlWorkBook.Sheets(1)
For i As Integer = 1 To Columns - 1
ColValue = ConvertNumberToString(i + 1)
chartRange = xlWorkSheet.Range("A3", ColValue & Row - 1)
EnergyChart.SetSourceData(chartRange)
Series = CType(EnergyChart.SeriesCollection(1), Excel.Series)
Next
With EnergyChart
.HasTitle = True
.ChartTitle.Font.Color = Color.SeaGreen
.ChartTitle.Font.Size = 11
.ChartTitle.Font.Name = "Calibri"
.ChartTitle.Text = ReportFileName
.ChartType = Excel.XlChartType.xlLine
End With
End Sub
Chart OK

Related

Adding labels to line chart with VBA

Right now I have the following code to display a line curve. The number of inputs can vary and I want the chart to clear and draw a new line curve every time the macro is run.
Sub addchart()
If ActiveSheet.ChartObjects.Count > 0 Then
ActiveSheet.ChartObjects.Delete
End If
Dim ws As Worksheet
Dim ch As chart
Dim ch1 As chart
Dim dt As Range
Dim i As Integer
i = Cells(Rows.Count, "I").End(xlUp).Row
Set ws = ActiveSheet
Set dt = Range(Cells(2, 10), Cells(i, 10))
Set ch = ws.Shapes.AddChart2(Width:=1300, Height:=300, Left:=Range("a13").Left, Top:=Range("a13").Top).chart
With ch
.SetSourceData Source:=dt
.ChartTitle.Text = "Deflection Curve"
.ChartType = xlLine
.SeriesCollection(1).Name = "Deflection"
End With
If Application.WorksheetFunction.Min(dt) > -50 Then
With ch.Axes(xlValue)
.MinimumScale = -50
.MaximumScale = 0
End With
End If
End Sub
The chart that is printed looks something like this
I'm trying to figure out how to add labels to arbitrary points to the chart. Two labels to be specific. One is at the minimum value. And one is the value at any arbitrary point on x-axis. Both x-values are known and will be taken as inputs from two cells on the sheet. Something like this.
The style of highlighting is unimportant. Thanks for the help!
P.S. - I'm new to VBA and I'm learning everything on the go. I look up what I need to do and then try and imitate whatever examples I see online. So it's possible the existing program I've written for the chart might have unnecessary steps or is inefficient in some way. I would appreciate it if someone had any tips to offer to improve it, even though it does the job. Thanks!
Try those for first steps making chart labels:
Dim chartname as string
chartname = "enter_a_name"
ActiveSheet.Shapes.AddChart2(227, xlLine).Name = chartname
With ActiveSheet.Shapes(chartname).Line
.Visible = msoTrue
.ForeColor.RGB = RGB(0, 0, 0)
.Transparency = 0
.Weight = 1.5
End With
Set my_chart = ActiveSheet.ChartObjects(chartname).Chart
'Delete all Autolabels
my_chart.SetElement (msoElementDataLabelNone)
'Enter format of axis (just if you want to)
'With my_chart.Axes(xlCategory) ' axis adjustment
'.CategoryType = xlCategoryScale ' not XlCategoryType.xlAutomaticScale | XlCategoryType.xlTimeScale
'.TickLabels.NumberFormat = "DD.MM.YYYY hh:mm"
'.TickLabels.Orientation = xlUpward
'End With
cols = Array("F", "L") ' columns containing labels
For j = 1 To my_chart.SeriesCollection.Count
Set sc = my_chart.SeriesCollection(j)
For i = 2 To sc.Points.Count
sc.Points(i).ApplyDataLabels
sc.Points(i).DataLabel.Text = Range(cols(j - 1) & i + x).Value ' x= starting row containing values /labels
Next i
Sub addchart()
If ActiveSheet.ChartObjects.Count > 0 Then
ActiveSheet.ChartObjects.Delete
End If
Dim ws As Worksheet
Dim ch As Chart
Dim dt As Range
Dim i As Integer
i = Cells(Rows.Count, "I").End(xlUp).Row
Set ws = ActiveSheet
Set dt = Range(Cells(2, 10), Cells(i, 11)) ' Added another column with the relevant values to highlight line chart
Set ch = ws.Shapes.AddChart2(Width:=1300, Height:=300, Left:=Range("a13").Left, Top:=Range("a13").Top).Chart
With ch
.SetSourceData Source:=dt
.ChartTitle.Text = "Deflection Curve"
.FullSeriesCollection(1).ChartType = xlLine
.SeriesCollection(1).Name = "Deflection"
.SeriesCollection(2).ChartType = xlColumnStacked 'the second column shows up as a bar chart along with the line chart
End With
If Application.WorksheetFunction.Min(Range(Cells(2, 10), Cells(i, 10))) > -30 Then
With ch.Axes(xlValue)
.MinimumScale = -30
.MaximumScale = 0
End With
End If
End Sub

How to add 2 labels in a chart using vba excel

I have created a chart using vba excel, then accidentally populate a graph that show the user and the counts which I prefer. But stupid of me I forgot to save, due to testing. Now I cant get the logic how to set it again. please help, thanks
Sample Data
Operator Counts Team
OPSHAF 123 A
OPSAJC 1245 B
OPSZAL 23 A
OPSJGY 162 C
OPSOSM 54 D
Sub CreateChart()
Dim rEmailRng As Range
Dim oEmailCht As Object
Dim cEmailCht As Chart
Dim coEmailCht As ChartObject
Dim iEmailRow As Integer
Dim sEmailSeries As Series
Dim scEmailSerCol As SeriesCollection
On Error Resume Next
Set wb = ThisWorkbook
Set wbsh2 = wb.Worksheets("Email")
Set coEmailCht = wbsh2.ChartObjects.Add(Range("E5").Left, Range("E5").Top, 500, 300)
coEmailCht = "Email Requests Processed" '& year
Set cEmailCht = coEmailCht.Chart
With cEmailCht
.HasLegend = False
.HasTitle = True
.Axes(xlValue).MinimumScale = 50
.Axes(xlValue).MaximumScale = 1500
.ChartTitle.Text = "Email Processed by Operator"
Set scEmailSerCol = .SeriesCollection
Set sEmailSeries = scEmailSerCol.NewSeries
With sEmailSeries
.Name = Range("A1").Offset(0, 1).Value
.XValues = Range(Range("A1").Offset(1, 0), Range("A1").End(xlDown))
.Values = Range(Range("A1").Offset(1, 1), Range("A1").Offset(1, 1).End(xlDown))
.ChartType = xl3DColumnClustered
End With
End With
Welcome To SO. If Your Objective is that axis label contain Count along with Operator then simply try
With sEmailSeries
'
.XValues = Range("A2:B" & Range("B2").End(xlDown).Row)
if you want team name also then
.XValues = Range("A2:C" & Range("C2").End(xlDown).Row)

Add two different types of Charts to Excel and Format them

I have a chart that is composed of two main things.
The first is a loop that creates a bunch of series based on values. Each of these series is an XY Scatter with Lines. Each of these Lines is coloured based on conditions using the Vlookup function in Excel. The first thing I need to correct is the Case part because it doesn't like the first instance of G. This only occurs when I have added the second chart.
The next thing I want is to create an XY Scatter with another Range, then apply Custom Data Labels to only those points. I can change the type of Chart the Series plots by using the answer below, which has been updated.
Dim age1 As Variant
Dim age2 As Variant
Dim per1 As Variant
Dim per2 As Variant
Dim id as Variant
Dim mp as Range
Dim yd as Range
id = Range(Range("A2"), Range("A2").End(xlDown)).Value2
age1 = Range(Range("C2"), Range("C2").End(xlDown)).Value2
age2 = Range(Range("D2"), Range("D2").End(xlDown)).Value2
per1 = Range(Range("E2"), Range("E2").End(xlDown)).Value2
per2 = Range(Range("E2"), Range("E2").End(xlDown)).Value2
Set mp = Range(Range("J2"), Range("J2").End(xlDown))
Set yd= Range(Range("E2"), Range("E2").End(xlDown))
ln = UBound(id) - LBound(id) + 1
Set cht = ws.ChartObjects(1).Chart
With cht
.ChartArea.ClearContents 'Clears the chart so a new one can be created
.ChartType = xlXYScatterLines 'Defines the Chart as a Scatter with Lines
For i = 1 To ln 'First Thing that creates many series
xdata = Array(age1(i, 1), age2(i, 1))
ydata = Array(per1(i, 1), per2(i, 1))
.SeriesCollection.NewSeries
.SeriesCollection(i).XValues = xdata
.SeriesCollection(i).Values = ydata
.SeriesCollection(i).Name = id(i, 1)
Next i
'Orginal method: .ChartType = xlXYScatter
.SeriesCollection.NewSeries
.SeriesCollection(.SeriesCollection.Count).XValues = mp
.SeriesCollection(.SeriesCollection.Count).Values = yd
.SeriesCollection(.SeriesCollection.Count).Name = "Series"
'New Method
.SeriesCollection(.SeriesCollection.Count).ChartType = xlXYScatter
End With
'end of creating charts
Set drng = Range(Range("A2"), Range("B2").End(xlDown) 'For the Vlookup
With ActiveSheet
For Each xycht In .ChartObjects
For Each mysrs In xycht.Chart.SeriesCollection
mysrs.MarkerStyle = xlMarkerStyleCircle
lnum = Application.VLookup(mysrs.Name, drng, 2, 0) 'This fails the first instance with G as a Type Mismatch Error.
' Select Case lnum
' Case "G"
' lColor = RGB(255, 0, 0)
' Case "D"
' lColor = RGB(0, 255, 0)
' Case "M"
' lColor = RGB(0, 0, 255)
' Case "A"
' lColor = RGB(0, 0, 0)
' Case Else
' lColor = RGB(255, 255, 255)
' End Select
' mysrs.MarkerBackgroundColor = lColor
' mysrs.Format.Line.Visible = msoFalse
' mysrs.Format.Line.Visible = msoTrue
' mysrs.Format.Line.ForeColor.RGB = lColor
Next
Set mypts = ws.ChartObjects(1).SeriesCollection(SeriesCollection.Count).Points(1).Apply 'This fails cause it needs an Object
mypts(mypts.Count).ApplyDataLabels
With mypts(mypts.Count).DataLabel
.ShowSeriesName = False
.ShowCategoryName = False
.ShowValue = False 'I need this tonot show Values, but my own Values.
' optional parameters
.Position = xlLabelPositionAbove
.Font.Name = "Helvetica"
.Font.Size = 10
.Font.Bold = False
End With
Next
End With
Use the ChartType property of the Series object...
.SeriesCollection(.SeriesCollection.Count).ChartType = xlXYScatter

VBA rounding up to the nearest 1E-n

I have created a Scatter Chart using VBA in excel.
The Y-Axis has a logarithmic scaling, as the values in my data ranges (300 data ranges with a few hundred thousand data points in each one) vary from 1 to 1E-10.
Is there a way to scale the Y axis automatically? As the maximum value can vary from chart to chart from 1 to 1E-5.
If not is there a way to round up to the nearest 1E-n? So I can scale my graph using the code below.
MyChart.Axes(xlValue).MaximumScale = "round up max value from my data range"
Thanks in advance
Charlie
For cond = 2 To wb.Worksheets.Count
Set ws = wb.Sheets(cond)
wsn = ws.Name
With ws
'Includes "Title" cell
Set ttl = .Cells(.Columns(1).Find(what:="Title", after:=Cells(1, 1)).Row, 1)
Set ttl2 = .Cells(ttl.Row, .UsedRange.Columns.Count)
Set rng1 = .Range(ttl, ttl2)
Set Data = .Cells(.Columns(1).Find(what:="*Pa)*", after:=Cells(1, 1)).Row + 2, 1)
Set Data2 = .Cells(.UsedRange.Rows.Count, .UsedRange.Columns.Count)
Set rng2 = .Range(Data, Data2)
myrng = Union(rng1, rng2).Address
End With
ws.Shapes.AddChart.Name = (wsn)
ws.Shapes(wsn).Chart.ChartType = xlXYScatterLinesNoMarkers
Set MyChart = ws.Shapes(wsn).Chart
MyChart.SetSourceData Source:=ws.Range(myrng), PlotBy:=xlColumns
MyChart.ApplyLayout (1)
MyChart.ChartTitle.Text = Title & " " & wsn
MyChart.Axes(xlValue, xlPrimary).AxisTitle.Text = "Pressure "
MyChart.Axes(xlCategory, xlPrimary).AxisTitle.Text = "Output”
MyChart.Axes(xlValue).ScaleType = xlLogarithmic
MyChart.Axes(xlValue).TickLabels.NumberFormat = "0.0E+00"
MyChart.Axes(xlValue).CrossesAt = 0.000000001
MyChart.Axes(xlValue).MaximumScale = “needs automating”
MyChart.Axes(xlCategory).ScaleType = xlLogarithmic
MyChart.Axes(xlCategory).MaximumScale = 10000
ws.ChartObjects(wsn).Left = ws.Range("A1").Left
ws.ChartObjects(wsn).Top = ws.Range("A1").Top
ws.ChartObjects(wsn).Height = 400
ws.ChartObjects(wsn).Width = 1200
MyChart.Axes(xlCategory, xlPrimary).HasMajorGridlines = True
MyChart.Axes(xlCategory, xlPrimary).HasMinorGridlines = True
ws.ChartObjects(wsn).Chart.Legend.Left = 1000
ws.ChartObjects(wsn).Chart.Legend.Width = 190
ws.ChartObjects(wsn).Chart.Legend.Top = 17.5
ws.ChartObjects(wsn).Chart.Legend.Height = 360
ws.ChartObjects(wsn).Chart.PlotArea.Width = 975
Next cond
I haven't tried this, but what about:
With MyChart.Axes(xlValue)
.MinimumScaleIsAuto = True
.MaximumScaleIsAuto = True
End With

Looping through Range1, Range2,...,Range(n) for adding chart data series

I would like to use a single range call within a for loop to add data series to a chart (XY line).
In my example, based on a users input to how many data series they want on a plot (1,2, or 3), ChartData(1), ChartData(2), and ChartData(3) as appropriate that would correspond to SeriesCollection(1), SeriesCollection(2), SeriesCollection(3).
Can't figure out what to use for the ranges.
Dim cb As ComboBox
Dim rge As range
Dim MyChart As Chart
Dim ChartData As range
Dim chartIndex As Integer
Dim ChartName(3) As String
Dim n As Long
Dim i As Long
Dim valid As Boolean: valid = True
m = Application.InputBox("Please enter the number of TML's to graph (1,2, or 3): ", "Select # of TML's", Type:=1)
For i = 1 To m
Set cb = TargetSheet.Shapes("ComboBox" & i).OLEFormat.Object.Object
Set rge = TargetSheet
If IsNumeric(m) And m <= 3 And m > 0 Then _
For a = 1 To m
chartIndex(a) = cb(a).ListIndex
For n = 3 To lastRowTarget2
Select Case chartIndex
Case n - 3
Set ChartData(a) = TargetSheet.range(TargetSheet.Cells(n, 5), TargetSheet.Cells(n, MyRange.Columns.Count - 2))
ChartName = TargetSheet.range("C" & n).Text
UserForm1.TextBox1.Value = TargetSheet.Cells(n, MyRange.Columns.Count).Value
UserForm1.TextBox2.Value = TargetSheet.Cells(n, MyRange.Columns.Count - 1).Value
UserForm1.TextBox3.Value = TargetSheet.Cells(n, 4)
End Select
Next n
Application.ScreenUpdating = False
Set MyChart = TargetSheet.Shapes.AddChart.Chart
With MyChart
.ChartType = xlLineMarkers
.HasTitle = True
.ChartTitle.Text = "Wall Thickness Trend based on Data Points"
.SeriesCollection.NewSeries
.SeriesCollection(a).Name = ChartName
.SeriesCollection(a).Values = ChartData
.SeriesCollection(a).XValues = TargetSheet.range(TargetSheet.Cells(1, 5), TargetSheet.Cells(1, MyRange.Columns.Count))
.SeriesCollection(a).Trendlines.Add Type:=xlLinear
.DisplayBlanksAs = xlInterpolated
.Axes(xlCategory, xlPrimary).HasTitle = True
.Axes(xlValue, xlPrimary).HasTitle = True
.Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = "Time (dd-mm-yyyy)"
.Axes(xlValue).MinimumScale = 0
.Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "Measured Wall Thickness (mm)"
.Legend.Delete
.Parent.Height = 350
.Parent.Width = 550
.Parent.Top = 100
.Parent.Left = 100
End With
Dim ser As Series
Set ser = MyChart.SeriesCollection(a)
ser.ErrorBar Direction:=xlY, Include:=xlErrorBarIncludeBoth, Type:=xlErrorBarTypeFixedValue, Amount:=1
Next a

Resources