I would like to export a complex data type to VBA from a C# .dll. Such as returning the data type: "System.Data.DataTable" to a VBA sub routine.
Minimal working example (MWE) below:
// C# .dll Code:
using System;
using System.Data; // So I can use DataTable as a type.
using System.Runtime.InteropServices; // Library required to allow early binding and hence gets intellisense working in VBA.
// So, it is required for "ClassInterface" and "ComDefaultInterface".
namespace ClassLibrary1
{
[ClassInterface(ClassInterfaceType.AutoDual)] // Used to expose the class to VBA.
public class Class1
{
public DataTable Test()
{
DataTable dtResults = new DataTable("PortfolioResults");
dtResults.Columns.Add("Date");
dtResults.Columns.Add("Price");
dtResults.Rows.Add(DateTime.Today, 100.52);
return dtResults;
}
}
}
The VBA code calls the method "Test" and would like to receive the 'DataTable' datatype from C#:
Option Explicit
Private Sub TestDotNetCall()
Dim testClass As New ClassLibrary1.Class1
Dim Results As DataTable
Results = testClass.Test
End Sub
VBA gives me the error message "Object variable of with block variable not set".
Note: I understand there is a "Microsoft.Office.Interop.Excel.DataTable object". But casting System.Data.DataTable to the Excel kind doesn't appear allowed.
ie.
using Interop_Excel = Microsoft.Office.Interop.Excel; // Library is required to allow Excel worksheet cells to talk to the C# COM add-in.
return (Interop_Excel.DataTable) dtResults;
VBA error message is now "Class does not support Automation or does not support expected interface".
What am I missing? How can I get such complicated types into VBA?