How do I set the X Axis to equal a predetermined range in excel using vb.net - vb.net

I have been able to create a graph using vb.net. The data is being displayed correctly however the X axis is incrementing 1, 2, 3... How do I specify a range for the X axis.
My code is:
Dim chartPage As excel.Chart
Dim xlCharts As excel.ChartObjects
Dim myChart As excel.ChartObject
Dim chartRange As excel.Range
oSheet.Cells(2).columnwidth = 4.29
oSheet.Cells(3).ColumnWidth = 5.71
oSheet.Range("D1", "P1").ColumnWidth = 6.14
oSheet.Cells(17).ColumnWidth = 9.29
oSheet.Cells(18).ColumnWidth = 12
oSheet.Cells(19).ColumnWidth = 7.86
xlCharts = oSheet.ChartObjects
myChart = xlCharts.Add(715, 30, 672, 360)
chartPage = myChart.Chart
chartRange = oSheet.Range("D3", "S" + CStr(RowCount))
chartPage.SetSourceData(Source:=chartRange)
chartPage.ChartType = excel.XlChartType.xlLine
Here is the spreadsheet that is being created:
Spreadsheet and chart created
Rather than the bottom axis of the chart being 1 threw 23 I need it to be the values in the Weeks column. (C3:C26)

Related

Type Mismatch Error in Word, but not in Excel or PowerPoint

I'm programming a custom chart add-in for Word that should behave the same as add-ins I've already done for Excel and PowerPoint. The code is very similar in all three programs, but I'm getting a baffling error in Word that doesn't occur in the other 2 programs.
Excel (works just fine):
Sub AddTextboxToChart()
Dim oChart As Chart
Dim oChtShp As Shape
Dim oLegShp As Shape
sChtName = ActiveChart.Name
ChtShpName$ = Right(sChtName, Len(sChtName) - InStrRev(sChtName, " ", Len(ActiveSheet.Name) + 1))
Set oChtShp = ActiveSheet.Shapes(ChtShpName$)
Set oChart = oChtShp.Chart
Set oLegShp = oChart.Shapes.AddTextbox(msoTextOrientationHorizontal, 100, 100, 100, 100)
oLegShp.Fill.ForeColor.RGB = RGB(0, 0, 0)
End Sub
PowerPoint (also works fine):
Sub AddTextboxToChart()
Dim oChart As Chart
Dim oChtShp As Shape
Dim oLegShp As Shape
If ActiveWindow.Selection.ShapeRange(1).HasChart Then
Set oChtShp = ActiveWindow.Selection.ShapeRange(1)
Set oChart = oChtShp.Chart
Set oLegShp = oChart.Shapes.AddTextbox(msoTextOrientationHorizontal, 100, 100, 100, 100)
oLegShp.Fill.ForeColor.RGB = RGB(0, 0, 0)
End If
End Sub
Word (errors on "Set oLegShp" line):
Sub AddTextboxToChart()
Dim oChart As Chart
Dim oChtShp As Shape
Dim oLegShp As Shape
If ActiveWindow.Selection.ShapeRange(1).HasChart Then
Set oChtShp = ActiveWindow.Selection.ShapeRange(1)
Set oChart = oChtShp.Chart
Set oLegShp = oChart.Shapes.AddTextbox(msoTextOrientationHorizontal, 100, 100, 100, 100) 'This line errors with Type Mismatch
oLegShp.Fill.ForeColor.RGB = RGB(0, 0, 0)
End If
End Sub
Excel and PowerPoint behave as expected, but Word errors out with a Type Mismatch when it tries to set the shape reference to an added text box. Any ideas or workarounds?
If you try to run the code, create a sample chart in Word, then set it to be floating in front of the text. Otherwise, Word sees it as an Inline Shape, which is a whole other can of worms.
I'm running Version 2205 (Build 15225.20288 Click-to-Run) under Windows 10.
(Edit) A kludge to get around the bug:
oChart.Shapes.AddTextbox msoTextOrientationHorizontal, 100, 100, 100, 100
For x = 1 To oChart.Shapes.Count
If oChart.Shapes(x).Left = LegLeft And oChart.Shapes(x).Top = LegTop Then
oChart.Shapes(x).Fill.ForeColor.RGB = RGB(0,0,0)
End If
Next x

Excel VBA array data source for Chartspace in Userform

I try to generate a barchart within an Excel Userform - Chartspace Is there any possibility to use VBA generated array data as source for the bar chart. I can only find description for Spreadsheet as source.
Private Sub UserForm_Activate()
Dim z As Long, s As Integer
Dim cc
Dim ch1
Dim pt
For z = 1 To 9
For s = 1 To 2
Spreadsheet1.ActiveSheet.Cells(z, s) = Sheets("Tabelle1").Cells(z, s)
Next
Next
Set cc = ChartSpace1.Constants
Set ChartSpace1.DataSource = Spreadsheet1 '<-- does it need linked to a spreadsheet?
Set ch1 = ChartSpace1.Charts.Add
ch1.Type = cc.chChartTypeLineMarkers
ch1.SetData 1, 0, "A2:A9"
ch1.SeriesCollection(0).SetData 2, 0, "B2:B9"
End Sub
Is the a other way to show a bar chart in a userform where I can use the array source?
Thanks a lot.
Perhaps this suggests how to do it:
http://msdn.microsoft.com/en-us/library/office/aa193650(v=office.11).aspx
This example (slightly modified so that I could test from the link above) creates a chart using literal data arrays.
Output Example
Code Example
Sub BindChartToArrays()
Dim asSeriesNames(1)
Dim asCategories(7)
Dim aiValues(7)
Dim chConstants
Dim chtNewChart
Dim myChtSpace As ChartSpace
asSeriesNames(0) = "Satisfaction Data"
asCategories(0) = "Very Good"
asCategories(1) = "Good"
asCategories(2) = "N/A"
asCategories(3) = "Average"
asCategories(4) = "No Response"
asCategories(5) = "Poor"
asCategories(6) = "Very Poor"
aiValues(0) = 10
aiValues(1) = 22
aiValues(2) = 6
aiValues(3) = 31
aiValues(4) = 5
aiValues(5) = 14
aiValues(6) = 12
Set myChtSpace = UserForm1.ChartSpace1
Set chConstants = myChtSpace.Constants
' Add a new chart to Chartspace1.
Set chtNewChart = myChtSpace.Charts.Add
' Specify that the chart is a column chart.
chtNewChart.Type = chConstants.chChartTypeColumnClustered
' Bind the chart to the arrays.
chtNewChart.SetData chConstants.chDimSeriesNames, chConstants.chDataLiteral, asSeriesNames
chtNewChart.SetData chConstants.chDimCategories, chConstants.chDataLiteral, asCategories
chtNewChart.SeriesCollection(0).SetData chConstants.chDimValues, chConstants.chDataLiteral, aiValues
UserForm1.Show
End Sub

Aspose VB.NET Bar Chart Value

I am setting up a bar chart that will end up exported into a PowerPoint slide. I've got it exporting perfectly fine but it has been requested that at the top of each bar the value of that bar is placed right above it. I've looked high and low and unfortunately haven't been able to find out how to do so.
I work as Social Media Developer at Aspose. Check the following sample code to set the custom labels as Values and setting the position of the label.
'Instantiate Presentation class that represents PPTX file
Dim pres As New Presentation()
'Access first slide
Dim sld As ISlide = pres.Slides(0)
' Add chart with default data
Dim chart As IChart = sld.Shapes.AddChart(ChartType.ClusteredBar, 0, 0, 500, 500)
'Setting chart Title
'chart.ChartTitle.TextFrameForOverriding.Text = "Sample Title";
chart.ChartTitle.AddTextFrameForOverriding("Sample Title")
chart.ChartTitle.TextFrameForOverriding.TextFrameFormat.CenterText = NullableBool.True
chart.ChartTitle.Height = 20
chart.HasTitle = True
'Set first series to Show Values
chart.ChartData.Series(0).Labels.DefaultDataLabelFormat.ShowValue = True
'Setting the index of chart data sheet
Dim defaultWorksheetIndex As Integer = 0
'Getting the chart data worksheet
Dim fact As IChartDataWorkbook = chart.ChartData.ChartDataWorkbook
'Delete default generated series and categories
chart.ChartData.Series.Clear()
chart.ChartData.Categories.Clear()
Dim s As Integer = chart.ChartData.Series.Count
s = chart.ChartData.Categories.Count
'Adding new series
chart.ChartData.Series.Add(fact.GetCell(defaultWorksheetIndex, 0, 1, "Series 1"), chart.Type)
chart.ChartData.Series.Add(fact.GetCell(defaultWorksheetIndex, 0, 2, "Series 2"), chart.Type)
'Adding new categories
chart.ChartData.Categories.Add(fact.GetCell(defaultWorksheetIndex, 1, 0, "Caetegoty 1"))
chart.ChartData.Categories.Add(fact.GetCell(defaultWorksheetIndex, 2, 0, "Caetegoty 2"))
chart.ChartData.Categories.Add(fact.GetCell(defaultWorksheetIndex, 3, 0, "Caetegoty 3"))
'Take first chart series
Dim series As IChartSeries = chart.ChartData.Series(0)
'Now populating series data
series.DataPoints.AddDataPointForBarSeries(fact.GetCell(defaultWorksheetIndex, 1, 1, 20))
series.DataPoints.AddDataPointForBarSeries(fact.GetCell(defaultWorksheetIndex, 2, 1, 50))
series.DataPoints.AddDataPointForBarSeries(fact.GetCell(defaultWorksheetIndex, 3, 1, 30))
'Setting fill color for series
series.Format.Fill.FillType = FillType.Solid
series.Format.Fill.SolidFillColor.Color = System.Drawing.Color.Red
'Set Data Labels for first series
For Each point As IChartDataPoint In series.DataPoints
Dim lbl As IDataLabel = point.Label
lbl.DataLabelFormat.ShowValue = True
lbl.DataLabelFormat.Position = LegendDataLabelPosition.OutsideEnd
Next point
'Take second chart series
series = chart.ChartData.Series(1)
'Now populating series data
series.DataPoints.AddDataPointForBarSeries(fact.GetCell(defaultWorksheetIndex, 1, 2, 30))
series.DataPoints.AddDataPointForBarSeries(fact.GetCell(defaultWorksheetIndex, 2, 2, 10))
series.DataPoints.AddDataPointForBarSeries(fact.GetCell(defaultWorksheetIndex, 3, 2, 60))
'Setting fill color for series
series.Format.Fill.FillType = FillType.Solid
series.Format.Fill.SolidFillColor.Color = System.Drawing.Color.Green
'Set Data Labels for first series
For Each point As IChartDataPoint In series.DataPoints
Dim lbl As IDataLabel = point.Label
lbl.DataLabelFormat.ShowValue = True
lbl.DataLabelFormat.Position = LegendDataLabelPosition.OutsideEnd
Next point
'Save presentation with chart
pres.Save("c:\data\AsposeChart.pptx", Aspose.Slides.Export.SaveFormat.Pptx)
Following is the sample from the above code to give an idea how to setup the labels.
'Set Data Labels for first series
For Each point As IChartDataPoint In series.DataPoints
Dim lbl As IDataLabel = point.Label
lbl.DataLabelFormat.ShowValue = True
lbl.DataLabelFormat.Position = LegendDataLabelPosition.OutsideEnd
Next point

Custom colors on bar chart using Zedgraph library

Am using Zedgraph chart library but I can't seem to be able to color a bar graph depending on a specific condition. Am following along with the example found on this tutorial.
In my case, if the value isn't above 50 -which is the student.pass_mark variable-, I want to color the bar red and if its above 50 I want to color it green. Below is my code. Which so far only gives me red even though I have values of 100, 80, 110 etc.
Dim subject As String
Dim grade As Decimal
Dim colors As Color() = {}
Dim subject_names As String() = {}
For i = 0 To student.no_of_subjects
ReDim Preserve colors(i)
ReDim Preserve subject_names(i)
subject = student.subject_name
grade = student.grade
Dim x As Double = CDbl(i) + 1
Dim y As Double = grade
Dim z As Double = 0
list.Add(x, y, z)
If grade < student.pass_mark Then
colors(i) = Color.Red
Else
colors(i) = Color.Green
End If
subject_names(i) = subject
Next
Dim myCurve As BarItem = myPane.AddBar("Student Subject", list, Color.Blue)
'Dim colors As Color() = {Color.Red, Color.Yellow, Color.Green, Color.Blue, Color.Purple}
myCurve.Bar.Fill = New Fill(colors)
myCurve.Bar.Fill.Type = FillType.Solid
myCurve.Bar.Fill.RangeMin = 0
myCurve.Bar.Fill.RangeMax = 4
myPane.Chart.Fill = New Fill(Color.White, Color.FromArgb(220, 220, 255), 45)
myPane.Fill = New Fill(Color.White, Color.FromArgb(255, 255, 225), 45)
' Tell ZedGraph to calculate the axis ranges
' Set the XAxis labels
myPane.XAxis.Scale.TextLabels = subject_names
' Set the XAxis to Text type
myPane.XAxis.Type = ZedGraph.AxisType.Text
ZedChart.IsShowPointValues = True
ZedChart.AxisChange()
ZedChart.Refresh()
Also, I want to draw a line across the whole chart that shows the pass_mark so that it is quickly visible that a student' has or hasn't passed a certain subject in comparison to the passmark
I don't know whether it is still relative but you can do multi-colored bar plots in ZedGraph.
You can find the tutorial here:
http://zedgraph.dariowiz.com/indexb806.html?title=Multi-Colored_Bar_Demo
In your case you can use FillType.GradientByColorValue I assume.
For the line you can simply add a LineObj to the myPane.GraphObjList

Aligning zeros in two Y Axis of DataVisualization.Charting.Chart

I have two series in a DataVisualization.Charting.Chart and two AxisY (AxisY1, and AxisY2). I was able to draw both series on a chart but the zeros for the left axis and right axis are not aligned. How can I align the zeros for the two axis?
NetChart.Series.Clear()
NetChart.Series.Add("Net")
NetChart.Series.Add("Net Cum.")
NetChart.Series(0).Points.Clear()
NetChart.Series(1).Points.Clear()
Dim netSaleDT As DataTable = SomeDataTable
netSaleDT.Columns.Add("CumulativeNet", GetType(Decimal))
Dim index As Integer = 0
Dim cumulSum As Decimal = 0
For Each drow As DataRow In netSaleDT.Rows
cumulSum += Convert.ToDecimal(drow("Net"))
drow("CumulativeNet") = cumulSum
NetChart.Series(0).Points.AddXY(drow("myMonth"), Convert.ToDecimal(drow("Net")))
NetChart.Series(1).Points.AddXY(drow("myMonth"), Convert.ToDecimal(drow("CumulativeNet")))
NetChart.Series(0).Points(index).AxisLabel = drow("myMonth")
index += 1
Next
NetChart.Series(0).YAxisType = System.Windows.Forms.DataVisualization.Charting.AxisType.Primary
NetChart.Series(1).YAxisType = System.Windows.Forms.DataVisualization.Charting.AxisType.Secondary
NetChart.Series(1).ChartType = DataVisualization.Charting.SeriesChartType.Line
NetChart.ChartAreas(0).AxisX.Interval = 2
NetChart.ChartAreas(0).AxisY.LabelStyle.Format = "C"
NetChart.ChartAreas(0).AxisY2.LabelStyle.Format = "C"
NetChart.Series(1).BorderWidth = 2
NetChart.Series(1).Color = Color.Blue
NetChart.ChartAreas(0).AxisY2.Enabled = DataVisualization.Charting.AxisEnabled.True
NetChart.ChartAreas(0).AxisY2.LabelStyle.Enabled = True
Is the axis properties set to auto?
If they are you need to manually set each axis programatically.
http://msdn.microsoft.com/en-us/library/system.windows.forms.datavisualization.charting.axis.minimum%28v=vs.110%29.aspx
When I set the min/max I usually do something like this:
Dim myChart As Excel.ChartObject = CType(xlCharts.Item(y), ChartObject)
Dim chartPage As Excel.Chart = myChart.Chart
chartPage.Axes(Excel.XlAxisType.xlCategory).minimumscale = minimum
chartPage.Axes(Excel.XlAxisType.xlCategory).maximumscale = maximum
This changes the x axis scale, to change the Y scale:
http://msdn.microsoft.com/en-us/library/system.windows.forms.datavisualization.charting.chartarea.axisy%28v=vs.110%29.aspx
and to change the secondary y scale:
http://msdn.microsoft.com/en-us/library/system.windows.forms.datavisualization.charting.chartarea.axisy2%28v=vs.110%29.aspx
Hope this helps
*Edit
Well i was trying to not give you the whole answer
But I suppose:
Dim myChart As Excel.ChartObject = CType(QoE.xLSheet1.ChartObjects(0), ChartObject)
Dim chartPage As Excel.Chart = myChart.Chart
chartPage.Axes(Excel.XlAxisGroup.xlPrimary).minimumscale = 0
chartPage.Axes(Excel.XlAxisGroup.xlSecondary).minimumscale = 0
Set the chart object to whatever chart you are trying to change, then set both the primary and secondary y axis to 0