I created a visual studio excel workbook project which contains ThisWorkbook class and I then included a functions class so that I can create my own excel function. I am trying to write a value to a cell using c# through the use of the function. I can write to the excel cell through the function class but only by creating a new application/workbook. So everytime I use this excel function, it will open new instance of excel. Is there a way I can write to a cell in the current excel workbook that is already opened?
Asked
Active
Viewed 7,248 times
2
-
Like I know I can do this simply in the ThisWorkbook class doing something like.. 'Excel.Worksheet worksheet = ((Excel.Worksheet)Application.Activesheet); Excel.Range firstcol = worksheet.get_Range("A1","A1"); firstcol.Value2 = "hello";' – George Oct 26 '11 at 15:53
-
Please post the code you are using so we can help improve it... or at least something that represents your code – TimothyP Oct 26 '11 at 15:55
2 Answers
2
Look, I tried and this code works:
private void ThisWorkbook_Startup(object sender, System.EventArgs e)
{
Excel.Worksheet ws = (Excel.Worksheet)(sender as Workbook).ActiveSheet;
System.Random rnd = new System.Random();
for (int i = 1; i <= 20; i++)
ws.Cells[i, 2] = rnd.Next(100);
}
so as you see you can access the Worksheet and use ws.Cells to manipulate cell values.
there are plenty of examples here:
Understanding the Excel Object Model from a .NET Developer's Perspective

Davide Piras
- 43,984
- 10
- 98
- 147
-
Would I be able to do something similar to this outside the ThisWorkbook class? I want to do the exact same thing in my function class but I'm unable to call since its a private void. Thanks – George Oct 26 '11 at 16:04
1
You probably create a new Excel application, instead of connecting to the active Excel application.
Use the GetActiveObject to get your reference to the Excel application object.

GvS
- 52,015
- 16
- 101
- 139
-
Yes I did create a new excel application. So GetActiveObject allows me to connect to the existing excel application currently open? – George Oct 26 '11 at 16:16