From: rogercnorris on
The following code was ported directly from some older VBA code that we
have. The VBA code works fine, but when we run it from VB.Net we get
an exception. What might be the problem?

The VB.Net code is simply trying to add a data series to a chart (using
Excel 2003). This is the code:

----

Dim worksheet as Excel.Worksheet
Dim xvalues, yvalues as Excel.Range

..
..
..

' Create new chart object embedded in the worksheet
Dim chart As Excel.Chart = CType(worksheet.ChartObjects,
Excel.ChartObjects).Add(400, 0, 640, 480).Chart
chart.ChartType = Excel.XlChartType.xlXYScatterLines

' add data series to the chart
CType(chart.SeriesCollection,
Excel.SeriesCollection).Add(Source:=application.Union(xvalues,yvalues))

----

When the final line of code is executed, we get the following error:

System.InvalidCastException
OleAut reported a type mismatch.
Stack trace:
at Microsoft.Win32.OAVariantLib.ChangeTypeEx(Variant source, Int32
lcid, Int32 cvType, Int16 flags)
at Microsoft.Win32.OAVariantLib.ChangeType(Variant source, Type
targetClass, Int16 options, CultureInfo culture)
at System.OleAutBinder.ChangeType(Object value, Type type, CultureInfo
cultureInfo)
at System.RuntimeType.ForwardCallToInvokeMember(String memberName,
BindingFlags flags, Object target, Int32[] aWrapperTypes, MessageData&
msgData)
at Microsoft.Office.Interop.Excel.SeriesCollection.Add(Object Source,
XlRowCol Rowcol, Object SeriesLabels, Object CategoryLabels, Object
Replace)


Oddly enough, the chart *is* created and the data series appears to
have been added properly. So what can we do to prevent this exception
from being thrown?

Some other relevant information... We're working in VB.Net 2003. The
interop library we're using is the Microsoft Excel 11.0 Object Library.