Gadziu
Gadziu

Reputation: 697

Loop through all open excel workbooks

I'm trying to build add-in to Excel with C#. I'm using this tutorial. So far was good, but I have problem with this part of code:

private void PopulateWorkbooks()
{
    var excel = Globals.ThisAddIn.Application;
    var workbooks = excel.Workbooks;
    foreach (var workbook in workbooks)
    {
        var book = workbook as Excel.Workbook;
        if (book != null)
        {
            var workbookViewModel = new WorkbookViewModel(book);
            this.workbookViewModels.Add(workbookViewModel);
        }
    }
}

in workbooks collection are no workbooks. The code doesn't go in loop...

Any ideas?

Upvotes: 2

Views: 1284

Answers (1)

ASH
ASH

Reputation: 20302

Just add a ListBox to your Form, pop in this code, and you're in business.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        Microsoft.Office.Interop.Excel.Application XL = null;

        private void Form1_Load(object sender, EventArgs e)
        {
            XL = (Microsoft.Office.Interop.Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
            foreach (Microsoft.Office.Interop.Excel.Workbook _wb in XL.Workbooks)
            {
                this.listBox1.Items.Add(_wb.Name.ToString());
            }
        }
    }
}

Upvotes: 1

Related Questions