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
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#.
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.
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!
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.
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.
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
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).
精彩评论