Excel 2010 Chart axis not shown up - vba

I am converting a EXCEL 2003 application to EXCEL 2010. Data are shown up fine but the axis does not show any more. which function to show the axis with automatic scale?
For Example: If you plot the following series in an Excel Line Chart. [0.22,0.33,0.44,0.55,0.66,0.77,0.88,0.99,1.1,1.21,1.32,1.43,1.54,1.65,1.76,1.87,1.98,2.09,2.2] Excel determines that the y-axis values should be [0,0.5,1,1.5,2,2.5] [How does Excel determine the axis values for charts?1. How to make the y-axis with the automatic values [0,0.5,1,1.5,2,2.5] shown in the chart?
Thanks
Updated with related codes -
With ActiveChart
.SeriesCollection(2).Select
'.SeriesCollection(2).AxisGroup = 2
.HasTitle = True
.ChartTitle.Text = OutputTitle & Chr(10) & ChartTitle2
.Axes(xlValue).HasTitle = True
.Axes(xlValue).AxisTitle.Text = AxisTitle1
.Axes(xlValue).AxisTitle.Font.Bold = False
.HasAxis(Excel.XlAxisType.xlCategory, Excel.XlAxisGroup.xlPrimary) = True
.Export Filename:=ExportFile, FilterName:="GIF"
End with
If I uncomment '.SeriesCollection(2).AxisGroup = 2, I will get the y axis to show but the x axis labels are messed up with mismatch with the Values.
Current chart -
Desired chart with scaled axis shown -

To make sure the axis is on use this:
With xlApp.ActiveChart
.HasAxis(Excel.XlAxisType.xlCategory, Excel.XlAxisGroup.xlPrimary) = True
End With
Range values are automatic unless otherwise specified like this:
' Set Axis Scales
With xlApp.Charts("Chart Name").Axes(2)
.MinimumScale = 100
.MaximumScale = 2000
.MajorUnit = 1000
.MinorUnit = 100
End With
Just to be a little more complete try explicitly addressing each value and category and see if that helps.
With xlApp.ActiveChart
.SeriesCollection(1).XValues = "='sheet name'!R21C4:R46C4"
.SeriesCollection(1).Values = "='sheet name'!R21C5:R46C5"
.SeriesCollection(1).Name = "='series name'"
.SeriesCollection(1).axisgroup = Excel.XlAxisGroup.xlPrimary
.HasAxis(Excel.XlAxisType.xlCategory, Excel.XlAxisGroup.xlPrimary) = True
.HasAxis(Excel.XlAxisType.xlValue, Excel.XlAxisGroup.xlPrimary) = True
.Axes(Excel.XlAxisType.xlCategory, Excel.XlAxisGroup.xlPrimary).HasTitle = True
.Axes(Excel.XlAxisType.xlCategory, Excel.XlAxisGroup.xlPrimary).AxisTitle.Characters.Text = "x axis"
.Axes(Excel.XlAxisType.xlValue, Excel.XlAxisGroup.xlPrimary).HasTitle = True
.Axes(Excel.XlAxisType.xlValue, Excel.XlAxisGroup.xlPrimary).AxisTitle.Characters.Text = "y axis"
End With
I see your axes group is set to 2, are you using dual axis?
Set it like this:
.SeriesCollection(2).axisgroup = Excel.XlAxisGroup.xlPrimary
*Edit*
To set autoscale on the axis:
.Axes(xlValue).MinimumScaleIsAuto = True
.Axes(xlValue).MaximumScaleIsAuto = True
.Axes(xlValue).MinorUnitIsAuto = True
.Axes().MajorUnitIsAuto = True
.Axes().DisplayUnit = xlHundreds

Related

Column Chart vb.net

I want to make a column chart of the occupation of machines per month. I have this data base:
And I'm using this code to make the chart:
private sub
rng1 = folhaexcel5.Range("B2:M2", "B3:M3")
grafico = folhaexcel5.Shapes.AddChart(xlColumns).Chart
grafico.SetSourceData(Source:=rng1)
grafico.HasTitle = True
grafico.ChartTitle.Characters.Text = "Occupation Rate of Machines"
grafico.Axes(XlAxisType.xlValue).MaximumScale = 100
grafico.Axes(XlAxisType.xlValue).HasTitle = True
grafico.Axes(XlAxisType.xlValue).axistitle.characters.text = "Occupation Rate (%)"
grafico.HasLegend = False
folhaexcel5.ChartObjects(1).Top = folhaexcel5.Range("p3").Top
folhaexcel5.ChartObjects(1).left = folhaexcel5.Range("p3").Left
folhaexcel5.ChartObjects(1).height = 300
folhaexcel5.ChartObjects(1).width = 1000
grafico.SeriesCollection(1).Interior.Color = Color.FromArgb(0, 124, 208)
grafico.SeriesCollection(1).Border.Color = Color.FromArgb(0, 55, 92)
End sub
When I run it, the chart is added to the excel file, but it's blank. And when I click in the chart to see the selected data this is showed to me:
I want to put line 2 as x-axis and line 3 as y-values. But it seems that i can't selecte these two lines. Anyone can help me?

Format datatable values in VBA

Currently working on a vba script that makes charts automatically. I would like to add a datatable which is done using: .HasDataTable = True
However I would like to show the values of series as percentages. Currently the value is defined as a Double containing all the values but not the right formatting. Using Format() or FormatPercent() will give the right values but returned in a String. This works for the datatable but not for the chart itself since it doesn't recognize the values anymore.
My question comes down to whether it is possible to show the values as percentages in both the datatable and the chart? Without VBA it is easily done by formatting the data in the cells itself. The problem is that for formatting a String is returned but for the graph Integers or Doubles are needed.
Below is part of the code. If I dim Ratio as String and use FormatPercent() I get the requested formatting but then the values in Ratio ar no longer doubles so it doesn't give the required chart.
Dim Ratio() As Double
Dim labels() As String
ReDim Ratio(1 To Height)
ReDim labels(1 To Height)
For Each Column In sArray
labels(i) = Sheets(DataSheetName).Cells(LabelsRow, Column)
Ratio(i) = Math.Round(Sheets(DataSheetName).Cells(LabelsRow + 3, Column), 2)
i = i + 1
Next Column
Set myChtObj = Sheets(DrawSheetName).ChartObjects.Add(Left:=Left, Width:=Width, Top:=Top, Height:=HeightGraph)
Dim srsNew1 As Series
' Add the chart
With myChtObj.Chart
.ChartArea.Fill.Visible = False
.ChartArea.Border.LineStyle = xlNone
.PlotArea.Format.Fill.Solid
.PlotArea.Format.Fill.Transparency = 1
.HasTitle = True
.ChartTitle.text = Title
.HasLegend = False
.Axes(xlValue).TickLabels.NumberFormat = "0%"
.Axes(xlCategory, xlPrimary).HasTitle = False
'add data table
.HasDataTable = True
' Make Line chart
.ChartType = xlLine
' Add series
Set srsNew1 = .SeriesCollection.NewSeries
With srsNew1
.Values = Ratio
.XValues = labels
.Name = "Ratio"
.Interior.Color = clr3 'RGB(194, 84, 57)
End With
End With

How to assign XValues for excel chart using VBA

I have this VBA function for drawing charts in Excel 2013:
Sub DrawChart2(obj_worksheetTgt As Worksheet, ByVal XLabels As Range, ByVal DataValues As Range, ByVal chartTitle As String, a As Integer, b As Integer)
'
'obj_worksheetTgt - Object worksheet on which to be placed the chart
'XLabels - Data range for X labels
'DataValues - Data range for Y values
'chartTitle - Chart title
'a - left border position of chart in pixels
'b - top border position of chart in pixels
With obj_worksheetTgt.ChartObjects.Add(a, b, 900, 300) ' Left, Top, Width, Height
With .Chart
.ChartType = xlBarClustered
Set .SeriesCollection(1).XValues = XLabels ' Here is the error
Set .SeriesCollection(1).Values = DataValues
.Legend.Position = -4107
.HasTitle = True
.chartTitle.Text = chartTitle
.chartTitle.Font.Size = 12
With .Axes(1).TickLabels
.Font.Size = 8
.Orientation = 90
End With
End With
End With
End Sub
I call the function this way:
ChartsWorksheet = "Summary"
Queryname = "query1"
chartTitle = "Values"
With .Worksheets("LastDayData").ListObjects(Queryname)
Set chart_labels = .ListColumns(2).DataBodyRange
Set chart_values = .ListColumns(6).DataBodyRange
End With
Call DrawChart2(.Worksheets(ChartsWorksheet), chart_labels, chart_values, chartTitle, 10, 10)
And I receive an error:
Runtime Error '1004':
Invalid Parameter
When I click debug it marks the row "Set .SeriesCollection(1).XValues = XLabels" in the function above.
In the documentation is written:
The XValues property can be set to a range on a worksheet or to an
array of values, but it cannot be a combination of both
So it should be able to take the given range as values for XValues, but I can't understand why this error appears.
Before you can set the Values and XValues of a series, you will need to add the series first. This is simple to do using the SeriesCollection.NewSeries method as show below:
With ActiveSheet.ChartObjects.Add(a, b, 900, 300) ' Left, Top, Width, Height
With .Chart
.ChartType = xlBarClustered
' need to add the series before you can assign the values/xvalues
' calling the "NewSeries" method add one series each time you call it.
.SeriesCollection.NewSeries
' now that the series is added, you may assign (not set) the values/xvalues
.SeriesCollection(1).XValues = XLabels
.SeriesCollection(1).Values = DataValues
End With
End With
You cannot use named ranges for .XValues or .Values, but you can change the .Formula property by replacing the series formula
For more information on editing the series formula see http://peltiertech.com/change-series-formula-improved-routines/
Note of caution, there is a bug in Excel 2013 that prevents you from using named ranges starting with "R" or "C" when using VBA to change the series formula; see http://answers.microsoft.com/en-us/office/forum/office_2013_release-excel/named-range-use-in-chart-series-formulas-causes/c5a40317-c33f-4a83-84db-0eeee5c8827f/?auth=1&rtAction=1466703182593

VBA Excel Graphing Add time to X-Axis

I am graphing a trend for a pump for a day, I am getting a sample data every minuet
I got the graph all working but the problem I am running into is trying to get the time on the X-axis. There is a column that shows the time each sample data was taken, but when I tried to add it, it put the time for every point in the chart. Because I have 1440 points in the chart, it was just a blob of unreadable text, I removed that code and right now I am doing without. But I would like to figure it out.
'Chart for Monday
With wBM.ActiveSheet.ChartObjects.Add(Left:=300, Width:=300, Top:=10, Height:=300)
.Chart.SetSourceData Source:=wBM.ActiveSheet.Range("B1:B1440"), PlotBy:=xlColumns
.Chart.ChartType = xlLine
.Left = rngChart2.Left
.Top = rngChart2.Top
.Width = rngChart2.Width
.Height = rngChart2.Height
.Chart.HasTitle = True
.Chart.ChartTitle.Text = "Monday " & Monday
.Chart.HasLegend = False
End With
This is my code so far. In Column D has the time for each point so it would be "D1:D1440".
Is there a way to only have 1 label for every 60 points, or 120? So that I don't have such a blob of labels?
Starting with sample data that looks like this:
I ran this macro to hide all labels which 'location' is not multiple of 5
Sub formateDataLabels()
Dim chrt As Chart
Set chrt = ActiveChart
Dim cnt As Long: cnt = 1
For Each lbl In chrt.SeriesCollection(1).DataLabels
If cnt Mod 5 <> 0 Then
lbl.Text = ""
End If
cnt = cnt + 1
Next lbl
End Sub
Result:
Note that the current code is simply set up to run on the selected chart. Change the 5 to whatever you need such as 50 or 100 and adapt to your current chart.

Setting dates on X axis

I'm trying to create a chart in Excel VBA and am having problems getting the X-Axis to display the dates correctly; the code is below:
Function CreateChart()
Dim objChart As Chart
ReDim detached_price(detachedProps.count - 1) As Double
ReDim detached_date(detachedProps.count - 1) As Date
ReDim semi_price(semiProps.count - 1) As Double
ReDim semi_date(semiProps.count - 1) As Date
Dim minDate As Date
Dim maxDate As Date
minDate = Date
Dim detachedCount As Integer
detachedCount = 0
Dim semiCount As Integer
semiCount = 0
Set objChart = Charts.Add
With objChart
.HasTitle = True
.ChartTitle.Characters.Text = "Price Paid"
.ChartType = xlXYScatter
.Location xlLocationAsNewSheet
.Axes(xlCategory, xlPrimary).HasTitle = True
.Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = "Date"
.Axes(xlCategory, xlPrimary).CategoryType = xlTimeScale
.Axes(xlCategory, xlPrimary).TickLabels.NumberFormat = "yyyy"
.Axes(xlCategory, xlPrimary).MinimumScaleIsAuto = True
.Axes(xlCategory, xlPrimary).MaximumScaleIsAuto = True
For Each prop In properties
Select Case prop.PropertyType
Case "Detached"
detached_price(detachedCount) = prop.Amount
detached_date(detachedCount) = prop.SellDate
detachedCount = detachedCount + 1
Case "Semi-detached"
semi_price(semiCount) = prop.Amount
semi_date(semiCount) = prop.SellDate
semiCount = semiCount + 1
End Select
If prop.SellDate < minDate Then
minDate = prop.SellDate
End If
If prop.SellDate > maxDate Then
maxDate = prop.SellDate
End If
Next
.SeriesCollection.NewSeries
.SeriesCollection(DETACHED).Name = "Detached"
.SeriesCollection(DETACHED).Values = detached_price
.SeriesCollection(DETACHED).XValues = detached_date
.SeriesCollection.NewSeries
.SeriesCollection(SEMI).Name = "Semi-Detached"
.SeriesCollection(SEMI).Values = semi_price
.SeriesCollection(SEMI).XValues = semi_date
End With End Function
The properties variable in the For..Each loop is populated, and fills the arrays correctly.
However, although the Scatter Graph data points are shown, the dates on the axis all show 1900.
I tried adding the lines:
.Axes(xlCategory, xlPrimary).MinimumScale = CDbl(minDate)
.Axes(xlCategory, xlPrimary).MaximumScale = CDbl(maxDate)
Which showed the correct years along the axis, but now all the data points for both series have disappeared.
I've tried a few other things, but it's been purely on a trial and error basis.
The data is as follows
The resulting charts are:
Correct dates, no data points
Incorrect dates, but we have data points
Even though I disagree with their definition of "common" date format :q, I think that #chiliNUT is on to something. There seems to be some problem with the coercion of the date format.
If you change all of your Date type variables to Double or Long, it should work.
For example change
ReDim detached_date(detachedProps.count - 1) As Date
to
ReDim detached_date(detachedProps.count - 1) As Double
or
ReDim detached_date(detachedProps.count - 1) As Long
This way the dates are not converted into String by the XValues method. They are stored as date serial numbers and the axis routine is able to coerce them successfully into the local date format.
Whats happening in your code is the Date types are coerced to String by the XValues method and the axis rendering routine seems to be unable to coerce them back into dates properly.
I don't think it is actually related to the international settings as I tried it using dates like this:
1/01/2013
1/01/2014
1/01/2015
1/01/2016
1/01/2017
1/01/2018
1/01/2019
1/01/2020
1/01/2021
which works in either system.
I think its just a bug in the axis rendering routine where its unable to properly coerce strings into dates.
I would be interested to hear from others more knowledgeable than me.
Also, I'm curious about this:
.SeriesCollection.NewSeries
.SeriesCollection(DETACHED).Name = "Detached"
.SeriesCollection(DETACHED).Values = detached_price
.SeriesCollection(DETACHED).XValues = detached_date
How does it know which series to reference? Is DETACHED a constant you have defined elsewhere?
I would think this would be better:
with objChart.SeriesCollection.NewSeries
.Name = "Detached"
.Values = detached_price
.XValues = detached_date
end with