0

This is a question that was taken from the learning's of my last question: Previous Question

I need to be able to send text to a selected worksheet that is already opened.

This, I think is close but it didn't work:

        string wb = cmb_BookName.Text.ToString();
        string ws = cmb_SheetName.Text.ToString();

        if (chkContainer.Checked)
        {
            Excel.Application oexcel = new Excel.Application();
            Excel.Workbook wkbk = (Excel.Workbook)oexcel.Workbooks[wb];
            Excel.Worksheet wksk = (Excel.Worksheet)wkbk.Sheets[ws];
            Range cellRange = wksk.Range["D48:D48"];
            cellRange.Value = cboContainer.Text;
        }

The code builds without errors but when running it stops at the line trying to get the workbook, see image.enter image description here

So basically my question still is how do I work with an excel workbook that is already opened?

Seems like most of the articles that I find are opening an excel file and then working with it. In my case, I need to work with an already opened excel workbook.

jrdnoland
  • 115
  • 10

1 Answers1

0

There are some helpful answers (some of them, not the accepted answer) to this question here: Accessing an open Excel Workbook in C#

But here is my summarized answer.

Try this:

First You must access the currently running application (if there are multiple instances of Excel running already, this might not work everytime)

using Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;

// I use a global application object
Application excelApp;

// Gets the first running instance of the Excel.Application
// If that fails, the error is caught, and a new application is created
try
{
   excelApp = (Application)Marshal.GetActiveObject("Excel.Application");
}
catch (COMException ex)
{
   excelApp = new Application
   {
      Visible = true
   };
}

Second Get the desired workbook by path, (must be windows style, i.e. "C:\Desktop\myWorkbook.xlsx")

Workbook myWorkbook = null;

foreach (Workbook xlWorkbook in excelApp.Workbooks)
{
   if (xlWorkbook.FullName == "<path to workbook>")
   {
      myWorkbook = xlWorkbook;
   }
} 
mattjr747
  • 84
  • 4