Programmatic saving of an existing excel file

N

Nikhil

I want to use C# to save the changes made to an existing excel file. The path
of the excel file is fixed and it can be assumed that the file is opened in
an excel window from before. All I want to do is write a program that
periodically saves whatever changes were made to the file (in the excel
window) since it was last saved. I have tried sending the Ctrl-S windows
message to excel and also tried playing around the
Microsoft.Office.Interop.Excel namespace, but to no avail. Is there a way to
do this that anyone is aware of? I am using Office 2007 but a solution for
Office 2003 or 2002 will also be of help to me.
 
C

Chip Pearson

All you need to do is

XLApp.ActiveWorkbook.Save;

where XLApp is your reference variable to the Excel application. For
periodic saving, create a timer object, set its interval to 5 minutes
(or whatever interval you want) and then in the event code use the
line above to save the workbook. This assumes that the workbook has
been saved at least once to disc so that it has a path name. Or, you
could expand the code with

if (XLApp.ActiveWorkbook.Path.ToString.Length == 0)
{
XLApp.ActiveWorkbook.SaveAs "C:\Test\Book1.xls";
}
else
{
XLApp.ActiveWorkbook.Save;
}


If a workbook has never been saved, the Path property has a Length of
0, so you need to save it to a file. If the workbook has been saved at
least once, the Path property has a Length > 0, so you can just Save.

Cordially,
Chip Pearson
Microsoft Most Valuable Professional
Excel Product Group, 1998 - 2009
Pearson Software Consulting, LLC
www.cpearson.com
(email on web site)
 
N

Nikhil

Thanks for response Chip.

However, I have another question: Suppose that excel.exe is already running
before I create the object XLApp. How can I dynamically attach XLApp to the
already running excel.exe process, so that I am able to save an excel
workbook which had been opened from before? Immediately after creating XLApp,
the number of workbooks in it are zero which means that we have to manually
attach it to a running process. Probably I am missing out a simple statement
here but this is where I am stuck as of now.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top