Click here to Skip to main content
15,889,462 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have multiple excel sheets opened in my windows system. I want to close a specific excel sheet using windows batch file.

Could you please help me with this.

What I have tried:

I have tried to close "Expenses.xlsx" excel sheet using the below command.

TASKKILL /FI "WINDOWTITLE eq Expenses - Excel" /f

But it's closing all the opened excel sheets, I want to close only one specific file out of multiple opened excel files.
Posted
Updated 18-Jul-19 6:15am
Comments
CHill60 17-Jul-19 4:12am    
You would have to have them open in separate instances of Excel.
nsvrao 17-Jul-19 4:54am    
yes, all the excel files are separate instances. I want to close one instance via a batch file.
CHill60 17-Jul-19 5:10am    
If your taskkill closed them all then they are not in separate instances of Excel - just multiple windows from the same instance
ZurdoDev 17-Jul-19 8:08am    
1. They are called workbooks, not sheets. Sheets are inside of a workbook so start by using the correct terminology and then you'll be able to find answers online.
2. What version of Excel? Older versions only supported a single instance. Start by looking in task manager to see if there are multiple instances of Excel or not.
nsvrao 18-Jul-19 1:56am    
Excel 2016... There are no multiple instances. Under one excel instance, multiple child processes are running.

1 solution

I doubt you'll find a way to do this from the command-line without using third-party tools. But if you're open to using an executable, you can write one yourself fairly easily. For example:
C#
using System;
using System.Runtime.InteropServices;

static class Program
{
    static void Main(params string[] args)
    {
        try
        {
            dynamic excel = Marshal.GetActiveObject("Excel.Application");
            dynamic workbooks = excel.Workbooks;
            foreach (string sheetName in args)
            {
                try
                {
                    dynamic workbook = workbooks[sheetName];
                    workbook.Close(false);
                }
                catch (COMException)
                {
                    Console.WriteLine("The workbook '{0}' is not open.", sheetName);
                }
            }
        }
        catch (COMException)
        {
            Console.WriteLine("Excel is not running.");
        }
    }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900