So basically my app triggers an excel macro, from a file, that updates the file and then closes it.
When I open the file I set the "DisplayAlerts = false" variable in order to ignore all popups and it works as expected in my computer... however, a colleague of mine tried to use it and for every file, he gets the popup asking if he wants to save all changes...
Checked other questions about the popups in excel but all suggested solutions use "oBook.Saved = true;" or "oBook.Close(false);", but these did not work for me.
my code is as follows:
using Microsoft.Office.Interop.Excel;
public static bool Trigger_Macro_From_File(string path)
{
ApplicationClass oExcel = null;
Workbook oBook = null;
try
{
string filename = Path.GetFileName(path);
string macro_name = "!some_macro";
string macro = #"'" + filename + #"'" + macro_name;
// Create an instance of Microsoft Excel
oExcel = new ApplicationClass
{
DisplayAlerts = false,
Visible = false
};
oBook = oExcel.Workbooks.Open(path);
RunMacro(oExcel, new Object[] { macro });
oBook.Save();
oBook.Saved = true;
return true;
}
catch (Exception ex)
{
return false;
}
finally
{
oBook?.Close(false);
System.Runtime.InteropServices.Marshal.ReleaseComObject(oBook);
oBook = null;
oExcel?.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(oExcel);
oExcel = null;
GC.Collect();
}
}
Does anyone know anything about this?
Thanks in advance.
You could double-check that no other "Microsoft Excel" process is running in the Task Manager.
Let's say at some point in your development process you started your program and open the workbook with something like
xlWorkbook = xlApp.Workbooks.Open(filePath);
Then you encountered an exception for some reason, and killed the program without closing the file properly (workbook.Close(..), app.Quit(..) and so on).
The Microsoft Excel process is still running in the background, and has a handle on the file you want to edit. So you cannot execute an instruction that saves the file under the same name. This is why the popup is appearing.
This scenario is taken from the point of view of the developer, but the same behavior could have happened on your coworker's computer if your app crashed without quitting properly, and gets re-started.
Also, be careful that finally statement might not always be executed, so double-check which scenario could cause your app to close without releasing the COM object.
Related
I am developing a Windows application where I manipulate Word Application. More specific, I am opening a Word Document but when I quit it and try to open another Word Document this Error comes out.
How to handle
System.Runtime.InteropServices.COMException (0x800706BA): The RPC server is unavailable. (Exception from HRESULT: 0x800706BA) at Microsoft.Office,Word.ApplicationClass.set_Visible(Boolean Prop)**
If I don't quit the Word Application this error does not come out.
Below I show you the functions that I open and quit the Word Application.
//function to open word Document located in a specific path
public static void openWordDocument(string fileName)
{
try
{
wordApplication.Visible = true;
string filePath = myPath + fileName;
WordApi.Document docx = wordApplication.Documents.Open(filePath);
}
catch (Exception ex)
{
MyLogger.Error(ex.ToString());
}
}
//function to quit wordApplication
public static void CloseWordApp() {
try {
Object wordAppObject = Marshal.GetActiveObject("Word.Application");
WordApi.Application wordApp = (WordApi.Application)wordAppObject; //cast Object to its actual type
wordApp.Quit();
}
catch (Exception ex) {
MyLogger.Error(ex.ToString());
}
I finally figured it out what is the problem.
The main problem was that when I quit it and try to open another Word Document,which opening another Word Document means get/create an Object of Word Application. In my case wordApp != null, after finalizing the application, so I had to create another Word Application Object and return it for the case.
//open word Document located in a specific path
public static void openWordDocument(string fileName)
{
try
{
wordApplication = createWordApplicationObject(wordApplication);
wordApplication.Visible = true;
string filePath = myPath + fileName;
WordApi.Document docx = wordApplication.Documents.Open(filePath);
}
catch (Exception ex)
{
MyLogger.Error(ex.ToString());
}
}
private static WordApi.Application createWordApplicationObject(WordApi.Application wordApp)
{
WordApi.Application wordAppFirstTime;
WordApi.Application wordApp1;
if (wordApp == null)
{
wordAppFirstTime = new WordApi.Application();
return wordAppFirstTime;
}
else
{
wordApp1 = new WordApi.Application();
return wordApp1;
}
}
With CloseWordApp() remain the same.
Most probably the exception is fired by the following line of code:
wordApplication.Visible = true;
You need to make sure the COM server is alive. Because after quitting the object becomes unavailable. I'd suggest setting such object references to null, so later we could check whether the application object is still alive. For example:
try
{
if (wordApplication == null)
{
wordApplication = new Word.Application();
}
wordApplication.Visible = true;
string filePath = myPath + fileName;
WordApi.Document docx = wordApplication.Documents.Open(filePath);
}
catch (Exception ex)
{
MyLogger.Error(ex.ToString());
}
I wanted to add a solution that works for me. We had this issue in a .net web service, along with other errors, like "the remote procedure call failed" on Word.Documents.Open(). i'll list all the things we tried, and finish with the solution.
we tried:
Make sure RPC service is up. Word is not corrupted, opens properly,
including the file we were opening.
restart server and service hosting the web application.
Rollback a windows update that occured the same day it stopped working.
Uninstalled the antivirus software.
We isolated the code to a third party app to validate it was the open()
method that caused the problem, and using different files as well. We
created a win form app, and consol app. We ran that small app as win
admin, a regular account as well as the account that runs the web
app.
We ran procMon.
we did a repair on word.
we installed Office all over, we tried 32 and 64bits version
Finale solution:
we deleted the user profile that runs the web app.
4 days to find that out. I'd thought i'd share my paine with the world. lol
while posting these lines, we are not sure why the local profile created this issue.
I have a C# (using Razor) Web Application that runs through my company's intranet.
I have been using ClosedXML to manage all of my Excel needs and it works great, however, now I need to run Macros inside Excel Files and apparently ClosedXML cannot do this, so I must use Excel Interop.
My code below gives the dreaded:
Microsoft Excel cannot access the file ... There are several possible
reasons: • The file name or path does not exist. • The file is being
used by another program. • The workbook you are trying to save has the
same name as a currently open workbook.
The file name and path DOES exist
I made sure that Excel is not even running on the server
The workbook is not open (see above).
Things I've tried.
I've tried to create security provisions for the C:\Windows\System32\config\systemprofile and SysWOW64\config\systemprofile.
(Side Note: I could not find IIS_USRS when I tried to add the security provisions - this may be the problem.)
I've also tried editing the Excel Application properties via dcomcnfg and I still get the same error.
here's what I'm trying to do:
//C# with Razor Syntax
#using MSExcel = Microsoft.Office.Interop.Excel
#using System.Runtime.InteropServices
#using System.Web
#using System.IO
string worksheetName = "Sheet1";
string[] macros = new string[] { "Module1.Reset_List()", "Module1.Run_Setup()"};
string workbookPath = HttpContext.Current.Server.MapPath(#"~/uploads/test.xlsm");
FileInfo xlsFile = new FileInfo(workbookPath);
string msg = (File.Exists(xlsFile.FullName)) ? "Found It!" : "Can't Find It...";
<p>#msg</p>; // <-- This always returns "Found It!"
//Create the Excel Object
MSExcel.Application xlsApp = new MSExcel.Application();
xlsApp.Visible = true;
try
{
//Identify the workbook (open the file)
// *** the error occurs on the line below *** //
MSExcel.Workbook xlsBook = xlsApp.Workbooks.Open(xlsFile.FullName);
xlsBook.Activate();
//Identify the worksheet
MSExcel.Worksheet xlsSheet = (MSExcel.Worksheet)xlsBook.Sheets[worksheetName];
xlsSheet.Activate();
foreach (string macro in macros)
{
xlsApp.Run(macro);
}
xlsBook.Save();
xlsBook.Close(false, "", false);
xlsApp.Quit();
}
catch (Exception e)
{
<p>#e.Message</p>
Marshal.ReleaseComObject(xlsApp);
xlsApp = null;
}
if (xlsApp != null)
{
Marshal.ReleaseComObject(xlsApp);
xlsApp = null;
}
Will be all unmanaged COM objects released in case if I use code like this
var worksheet = new Application().Workbooks.Add().Worksheets.Add();
Marshal.ReleaseComObject(worksheet);
instead of code like this
var excel = new Application();
var workbook = excel.Workbooks.Add();
var worksheet = workbook.Worksheets.Add();
Marshal.ReleaseComObject(excel);
Marshal.ReleaseComObject(workbook);
Marshal.ReleaseComObject(worksheet);
?
If there is some documentation please send a link in answer.
Actually, both code samples will leave an Excel process running in the background. You need to call Application.Quit() on the application object, for example. The following works:
private static void DoExcel()
{
var application = new Application();
var workbook = application.Workbooks.Add();
var worksheet = workbook.Worksheets.Add();
// Name that this will be saved as
string name = workbook.FullName + ".xlsx";
string fullPath = Path.Combine(Directory.GetCurrentDirectory(), name);
// If a file of the same name exists, delete it so that we won't be prompted if
// we want to overwrite it when we save
if (File.Exists(fullPath))
File.Delete(fullPath);
// Save the workbook - otherwise we may be prompted as to whether we want to save when we go to quit
workbook.Save();
// Quit the application
application.Quit();
// Release the references
Marshal.ReleaseComObject(worksheet);
Marshal.ReleaseComObject(workbook);
Marshal.ReleaseComObject(application);
// Release the .NET reference and run the garbage collector now to make sure the application is closed immediately
worksheet = null;
GC.Collect();
GC.WaitForPendingFinalizers();
}
A few other good things to remember: I didn't use it here, but there's a Marshal.FinalReleaseComObject method that's very useful in these cases. Also, again I didn't use this in my code sample, but the Marshal.ReleaseComObject method returns the current count, so you could always do the release in a loop if you wanted to make sure the count reached zero:
while (Marshal.ReleaseComObject(comObject) > 0) { }
You can also use this for debugging purposes - e.g.
int count = Marshal.ReleaseComObject(comObject);
Trace.TraceInformation("Current COM object reference count: " + count.ToString());
I) Global Explanation
Hello,
I'm developing an app in C# using Microsoft.Office.Interop.Excel. In my case I implement some olds macros stored in a file to an Excel Workbook, opened by C#, to upgrade them without re-coding macros in my app.
Globally there is my process in my app :
The user select an updated macro,
I check if the macro require something :
Here I set the register Key CURRENT_USER\SOFTWARE\Microsoft\Office\[office_ID].0\Excel\Security\AccessVBOM to 1 for allows macro/VBProject modifications
I instantiate an Excel app with a new workbook
I set optimization Excel execution parameters (disable refresh... that kind of stuff)
I add my macro, stored in a file, to the workbook
I execute the macro through Excel
I remove the macro from the Excel
I unset optimizations Excel executions parameters
I reset registers keys (.../AccessVBOM = 0)
II) My problem and my research result
In the "I add my macro, stored in a file, to the workbook" part, when I used the following instruction to add a VBProject to the workbook (required to add the macro) I get an error 800A03EC.
/// wb is a workbook object
VBComponent module = wb.VBProject.VBComponents.Add(vbext_ComponentType.vbext_ct_StdModule);
This error is send with a message (grossly traduce) : "The access to VB Project are not trust."
As I see on the Internet, this error occurs when an option in Excel isn't correctly set. This option can by handle with the CURRENT_USER\SOFTWARE\Microsoft\Office\[office_ID].0\Excel\Security\AccessVBOM register key.
And I'm building my app with a register key management for avoid this problem.
And as you will see on the debug display part, we can see the option is correctly set on the execution.
My question : there is another case when this error occurs?
III) Debug analyse
When I catch the ComException, I use the following to display registers keys values.
/// RequirementManager is my own class, use to set and unset endpoints computers parameters, before and after each user action
RegistryKey reg;
for (int i = RequirementManager.EXCEL_ID_HANDLED_MIN; i < RequirementManager.EXCEL_ID_HANDLED_MAX; i++)
{
reg = Registry.CurrentUser.CreateSubKey(#"SOFTWARE\Microsoft\Office\" + i + #".0\Excel\Security\", RegistryKeyPermissionCheck.ReadSubTree);
Debug.WriteLine(String.Format(#"Value of CURRENT_USER\SOFTWARE\Microsoft\Office\{0}.0\Excel\Security\AccessVBOM = {1}", i, reg.GetValue("AccessVBOM")), "Debug");
reg.Close();
}
reg = null;
And here is the console output of this lines :
Debug: Value of CURRENT_USER\SOFTWARE\Microsoft\Office\11.0\Excel\Security\AccessVBOM = 1
Debug: Value of CURRENT_USER\SOFTWARE\Microsoft\Office\12.0\Excel\Security\AccessVBOM = 1
Debug: Value of CURRENT_USER\SOFTWARE\Microsoft\Office\13.0\Excel\Security\AccessVBOM = 1
Debug: Value of CURRENT_USER\SOFTWARE\Microsoft\Office\14.0\Excel\Security\AccessVBOM = 1
Debug: Value of CURRENT_USER\SOFTWARE\Microsoft\Office\15.0\Excel\Security\AccessVBOM = 1
Debug: Value of CURRENT_USER\SOFTWARE\Microsoft\Office\16.0\Excel\Security\AccessVBOM = 1
As you can see, the option is correctly set when the error occurs. And all instance of Excel are closed before the modification of register keys, for avoid problem. I use similar algorithm to modify this range of register keys, like a lazy boy.
Any idea are welcome
Regards, Dykoine
IV) Answer Reaction
#prizm1 This parameter if macro are allowed or not (display orange warning message), and on my computer (while test) I set it to allow all macro.
After test, I can see this option doesn't protect the user, because we can open an Excel file with C# and execute a macro in it without be block by this option even if you use "disabled all without notification".
Here the code which haven't made any problems with putting VBA into an Excel file. Maybe you need to save it to disk first before entering the Code, since the Project is determined by the filename. Just an addition, and no real solution:
public bool injectVBA(String scriptText, String target)
{
VBProject found = null;
Access.Application currApplication = this.currentInstance.Application;
if (target.Equals("") || scriptText.Equals(""))
return false;
foreach (VBProject vb in currApplication.VBE.VBProjects)
{
if (currApplication.CurrentDb().Name.Equals(vb.FileName))
{
found = vb;
break;
}
}
if (found != null)
{
foreach (VBComponent foundComponent in found.VBComponents)
{
if (foundComponent.Name.Equals(target))
{
return true;
}
}
VBComponent module = found.VBComponents.Add(vbext_ComponentType.vbext_ct_StdModule);
module.Name = target;
module.CodeModule.AddFromString(scriptText);
module.Activate();
//currApplication.DoCmd.OpenModule(target, Type.Missing);
currApplication.DoCmd.Save(Access.AcObjectType.acModule, target);
return true;
}
else
{
return false;
}
}
I want to try the Windows form application that converts a office file (Excel, Word, Powerpoint) into a PDF file.
My client's PC will not install Visual Studio and Office version is 2007.
My application uses Microsoft.Office.Iterop.Excel.dll to covert to the PDF format.
This dll file cannot be found on my client's PC and an error has occurred as following.
System.AugumentException: Value does not fall within the expected range.
at Microsoft.Office.Interop.Excel._Workbook.ExportAsFixedFromat(.......)
How can I solve this problem?
My code is following
public bool ExportWorkbookToPdf(string workbookPath, string outputPath)
{
// If either required string is null or empty, stop and bail out
if (string.IsNullOrEmpty(workbookPath) || string.IsNullOrEmpty(outputPath))
{
return false;
}
// Create COM Objects
Microsoft.Office.Interop.Excel.Application excelApplication;
Microsoft.Office.Interop.Excel.Workbook excelWorkbook;
// Create new instance of Excel
excelApplication = new Microsoft.Office.Interop.Excel.Application();
// Make the process invisible to the user
excelApplication.ScreenUpdating = false;
// Make the process silent
excelApplication.DisplayAlerts = false;
// Open the workbook that you wish to export to PDF
excelWorkbook = excelApplication.Workbooks.Open(workbookPath);
MessageBox.Show(workbookPath);
// If the workbook failed to open, stop, clean up, and bail out
if (excelWorkbook == null)
{
excelApplication.Quit();
excelApplication = null;
excelWorkbook = null;
MessageBox.Show("in null");
return false;
}
var exportSuccessful = true;
try
{
// Call Excel's native export function (valid in Office 2007 and Office 2010, AFAIK)
excelWorkbook.ExportAsFixedFormat(Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF, outputPath);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
// Mark the export as failed for the return value...
exportSuccessful = false;
// Do something with any exceptions here, if you wish...
// MessageBox.Show...
}
finally
{
// Close the workbook, quit the Excel, and clean up regardless of the results...
excelWorkbook.Close();
excelApplication.Quit();
excelApplication = null;
excelWorkbook = null;
}
// You can use the following method to automatically open the PDF after export if you wish
// Make sure that the file actually exists first...
if (System.IO.File.Exists(outputPath))
{
MessageBox.Show(outputPath);
System.Diagnostics.Process.Start(outputPath);
}
return exportSuccessful;
}
As already said in the comments, each client needs to install the 2007 Microsoft Office Add-in: Microsoft Save as PDF. It doesn't matter if you are on Windows 8.1 or have any PDF reader installed. You need that Add-in to write PDFs with Office 2007. (You don't need any Add-In with Office 2010 or 2013.)