This is a simple solution without any error trapping etc.
In your C# project,
1. Add
using System.Runtime.InteropServices;
2. Add areference to
Microsoft Excel nn.n Object Library
where nn.n is a version number e.g. 1.0 for Excel/XP etc.
3. Now you can get hold of the open Excel session as follows:
Excel.Application xlObj =
(Excel.Application)Marshal.GetActiveObject("Excel.Application");
WARNINGS:
1. This will fail if there is no existing session of Excel.
2. You will always get the oldest session if multiple Excel sessions exist.
It might be wise to:
private void button3_Click(object sender, EventArgs e)
{
Excel.Application xlObj =
(Excel.Application)Marshal.GetActiveObject("Excel.Application");
MessageBox.Show(xlObj.ActiveCell.Value2.ToString());
}
1. Set the UserControl property of xlObj to false
2. Then, to set the visible property to false (to avoid conflicts between
the automation and interactive sessions which are one and the same thing).
To Test:
1. Create a new session of Excel
2. Add a button to a form in a Windows Application project , say button3
3. Type something in cell A1 of Excel & ensure that the cursor is in cell A1
afterwards.
Run the application and then Click the button (for whose click event you
will have added) the following code:
PS: C# is extremely hardwork when working with Excel because it does not
support optional arguments (as VB.NET does) and overloading in this context
creates clutter (I think).