MadSeb
MadSeb

Reputation: 8254

Launch Excel from C# and close it on "Save"

I want to do the following with C# and Microsoft Excel:

1 - The user chooses a file.

2 - Micorosft Excel is shown to edit that file.

3 - As soon as the user clicks Excel's "Save" button Microsoft Excel should close.The user shouldn't have to click on exit.

Any idea on #3 ?

Regards, Sebastian

Upvotes: 4

Views: 1211

Answers (7)

Hans Olsson
Hans Olsson

Reputation: 55049

You could have a Excel macro handle the BeforeSave event, cancel the save initiated by the user, save the file in the macro and after saving you'd be in your macro and could then close Excel.

So maybe something like:

Private Sub myBeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
    If Not HandlingBeforeSave Then
        HandlingBeforeSave = True
        Cancel = True
        Me.Save
        Application.Quit    
    End If
End Sub

This kb article describes adding a Macro to Excel from C#.

Upvotes: 1

chiccodoro
chiccodoro

Reputation: 14716

I had a similar issue, however I wait until the user closes Excel. See my "solution" at Excel automation: Close event missing.

I find it somehow unintuitive to close excel when the user hits "save". If you insist on the "save" event, you might want to watch the file metadata change as soon as the user saves (e.g. the last modified date).

Upvotes: 0

Zeal
Zeal

Reputation: 368

I am not sure if this helps, but I think it is close to your need http://www.c-sharpcorner.com/UploadFile/jodonnell/Excel2003fromCSharp12022005021735AM/Excel2003fromCSharp.aspx

Upvotes: 0

SLaks
SLaks

Reputation: 888077

You could handle the Workbook's BeforeSave event, then run a timer that checks the Saved property every ten seconds, and closes Excel if it's true.

You should exercise caution when closing Excel, since your users will be very angry if you close a (different) file that they're working on.

Upvotes: 0

Adam
Adam

Reputation: 3013

You could use VSTO for Excel. Gives you the ability to write C# code against the Excel object model. Should be able to do exactly what you want.

Still though, SWeko has a good point. You will need to figure out how to determine if it is supposed to close on save. If you don't every save would close Excel.

Upvotes: 0

STO
STO

Reputation: 10658

Also you may use FileSystemWatcher class to catch up saving moment, and kill Excel on it. Of course, if you know where user have to save file.

Upvotes: 0

SWeko
SWeko

Reputation: 30912

My Interop is a bit rusty, but I think there was an event that Excel fires when it saves a file.

However, I think this is a very dangerous feature to implement, since, in my experience, interop tends to be a bit non-deterministic :). Imagine what will happen if the save handler is active when the user is using Excel outside of your application - he clicks on save, and Excel dissapears!

Upvotes: 0

Related Questions