Mark
Mark

Reputation: 43

Create Horizontal Line in Excel Chart with Macro

At work, I have made a macro to format and chart out data that comes from testing the parts we make. The values have to be within a certain range, so I would like to add lines to the charts denoting where the tolerance limits are.

For example, one parameter is a voltage value for a certain signal. It must be between .271 and .451 to be in spec, so I would like to add lines at those values on that chart.

Other charts are measuring different things and would have different values, but the basic principle is the same.

The number of data points per signal is not the same, but is usually quite large, around a couple thousand each.

I have found a couple of different options around the internet involving the drawing tools or adding a new data series to the charts, but I am not well versed in those aspects of excel macros. In fact, I don't think I can find the page that I first found the data series idea at.

Upvotes: 1

Views: 12054

Answers (2)

Tim Mayes
Tim Mayes

Reputation: 574

Assuming you are using an XY Scatter chart, just create a couple of data points and add it as a new series. For example, enter your data as shown in A1:B6 and then add that entire range as a series. You'll get two lines. Obviously, the X and Y values should be calculated from your original data.

enter image description here

Upvotes: 0

Tim Williams
Tim Williams

Reputation: 166560

A new series for each line is the best approach.

 'add a line series with line but no markers
    Sub AddLineSeries(cht As ChartObject, sName As String, xvals, _
                       yvals, SeriesColor As Long)
        Dim s As Series
        Set s = cht.Chart.SeriesCollection.NewSeries
        With s
            .Name = sName
            .Values = yvals
            .XValues = xvals
            .MarkerBackgroundColor = xlNone
            .MarkerForegroundColor = SeriesColor
            .MarkerStyle = xlMarkerStyleNone
            With .Border
                .Weight = xlThin
                .Color = SeriesColor
            End With
        End With
    End Sub

Usage (adding one line for each cut-off):

'cht is the chart object
'minX/maxX are x-axis values you want to plot the line for
'qcMin/Max are the y-axis values for your lower/upper cut-offs
'Array() just creates an array of values to pass to the chart for plotting, since
'   we're not using values from a worksheet for this series
AddLineSeries cht, "QC Min", Array(minX, maxX), Array(qcMin, qcMin), _
              RGB(255, 0, 0)
AddLineSeries cht, "QC Max", Array(maxX, maxX), Array(qcMax, qcMax), _
              RGB(255, 0, 0)

Upvotes: 1

Related Questions