I've been successfully starting Excel and opening a workbook from C# without problems for several weeks. Today, one of our developers made some changes to the Excel workbook we automatically open by adding a some VBA code to the workbook. Specifically, he added a function in a Module called Module1, with the following code:
Function numdays_inmonth(mydate As Variant)
tmpdate = Year(mydate) & "-" & (Month(mydate) + 1) & "-" & 1
tmpdate = DateAdd("d", -1, tmpdate)
numdays_inmonth = Day(tmpdate)
End Function
One of the cells in the workbook uses this function. If I open the file by double clicking on it from explorer, it opens and runs perfectly fine. If I use the following code to open it, I get the "Can't find project or library"
ExcelDataForAccount excelData = new ExcelDataForAccount();
m_excelByAccountID.Add(a.AcctID, excelData);
excelData.Application = new Microsoft.Office.Interop.Excel.Application();
excelData.Application.Visible = true;
excelData.Application.WorkbookBeforeClose += new Microsoft.Office.Interop.Excel.AppEvents_WorkbookBeforeCloseEventHandler(Application_WorkbookBeforeClose);
string destinationFile = GetGreeksSheetForAccountFileName(a);
string destinationDoc = System.IO.Path.Combine(GetLocalFileCachePath(), destinationFile);
System.IO.
File.Copy(m_configuration.TemplateFileLocation, destinationDoc, true);
excelData.WorkbookFilename = destinationFile;
MSExcel.Workbook w = null;
try
{
w = excelData.Application.Workbooks.Open(destinationDoc,
false, false,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,true,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing);
excelData.Workbook = w;
excelData.Account = a;
// Using a cast here to avoid compiler warning regarding the Excel.Worksheet class inherits from multiple interfaces.
// _Worksheet, which has a method Activate, and WorkbookEvents_Event which has an event called Activate
((MSExcel._Worksheet)(excelData.MainWorksheet)).Activate();
What could be causing this? I have tried changing the function to this:
Function numdays_inmonth(mydate As Variant)
Dim tmpdate as Date
tmpdate = Year(mydate) & "-" & (Month(mydate) + 1) & "-" & 1
tmpdate = DateAdd("d", -1, tmpdate)
numdays_inmonth = Day(tmpdate)
End Function
which will allow me to continue though that function, but then I get the same error over and over in various parts of the VBA code. Usually, adding Dim statements fixes the problem, but I hit a line in the VBA where a call to the Str function fails and nothing but commenting out the line of code in VBA seems to help
Any ideas? I'd like to know the cause as much as a workaround, because I would hate it to happen when we are in production. This Excel file is changed often and not always tested against the applicaiton which launches it.