Setting a value in an Excel cell using C#

E

Emmanuel

Hi,

I 've managed to run successfully the example provided by the Microsoft
Q302901 - "How To Build an Office COM Add-in by Using Visual C# .NET"
article http://support.microsoft.com/default.aspx?scid=kb;en-us;302901

I want to change the button_click event code so that, when the button is
pressed, a value is written at the cell A1 of the active sheet.

I tryied the following code:

private void MyButton_Click(CommandBarButton cmdBarbutton,ref bool cancel)
{
// Get the active worksheet.
object sheet = applicationObject.GetType().InvokeMember("ActiveSheet",
BindingFlags.GetProperty, null, applicationObject, null);
// Get range A1
object range = sheet.GetType().InvokeMember("Range",
BindingFlags.GetProperty, null, sheet, new object[] {"A1", Missing.Value});
// Set the value "Hello world" to that range.
range.GetType().InvokeMember("Value", BindingFlags.SetProperty, null,
range, new object[] {"Hello world"});
}

The above code works fine for the first two invocations. But when the third
invocation that sets the value of the range is run, the application throws
an exception. If I catch the exception inside a try {} catch{} I get the
message:
"Exception has been thrown by the target of an invocation." in the
Exception.Message property
and
"mscorlib" in the Exception.Source property.

Does anyone know why I cannot set a property although I can get the
properties right ?

Thanks

Emmanuel
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top