Click to See Complete Forum and Search --> : Passing optional arguments to Interop methods


Bogus
December 3rd, 2005, 12:15 PM
How to pass optional argument in Managed C++ code to the method accessed via COM.
My problem:
I try to operate with MS Excel objects. Sheets object Add method has several optional arguments which I try to omit.
MS Excel Programmers guide says:
"expression.Add(Before, After, Count, Type)
...
Before Optional Variant. An object that specifies the sheet before which the new sheet is added.
After Optional Variant. An object that specifies the sheet after which the new sheet is added.
...
If Before and After are both omitted, the new sheet is inserted before the active sheet."

In managed C++ I have the following code line:

using namespace Interop;
using namespace Interop::Excel;
Excel::Sheets *m_sheets;
/*m_sheets has been initialised with m_sheets = m_book->get_Worksheets(); and so on*/
m_sheets->Add( optionalArgument, optionalArgument, __box(howManySheets), __box(XlSheetType::xlWorksheet));


Exact question:
How to declare and initialise optionalArgument not to obtain:
System.Runtime.InteropServices.COMException - Exception from HRESULT 0x800A03EC ?

NoHero
December 3rd, 2005, 12:19 PM
By passing NULL?

Bogus
December 3rd, 2005, 12:53 PM
m_sheets->Add( __box(0), __box(0), __box(ilesheets-count), __box(XlSheetType::xlWorksheet)); //xlWorksheet);

and

m_sheets->Add( 0, 0, __box(ilesheets-count), __box(XlSheetType::xlWorksheet)); //xlWorksheet);


gives the same exception. (NULL is defined as 0)
NB: Argument type is "System::Object __gc *"

cilu
December 3rd, 2005, 03:04 PM
You can't box a value/literal. You can box a value type instance.

int val = 0;
m_sheets->Add( __box(val), __box(val), __box(ilesheets-count), __box(XlSheetType::xlWorksheet));

But why don't you simply pass a NULL?

m_sheets->Add(NULL, NULL, __box(ilesheets-count), __box(XlSheetType::xlWorksheet));

NoHero
December 3rd, 2005, 04:54 PM
But why don't you simply pass a NULL?

Wouldn't that be the same as:

m_sheets->Add( 0, 0, __box(ilesheets-count), __box(XlSheetType::xlWorksheet)); //xlWorksheet);

As the OP stated? ;)

David Anton
December 3rd, 2005, 07:42 PM
How to pass optional argument in Managed C++ code to the method accessed via COM...


Use System.Reflection.Missing.Value

David Anton
www.tangiblesoftwaresolutions.com
Instant C#: VB.NET to C# Converter
Instant VB: C# to VB.NET Converter
Instant C++: C# to C++ Converter
Instant J#: VB.NET to J# Converter
Clear VB: Cleans up outdated VB.NET code

Bogus
December 5th, 2005, 06:24 AM
Thanks a lot. THIS IS WORKING!!!