Excel c# Issue - formula not being recalculated - c#

I am working on a document-level excel project. This is the third version.
One of the worksheet contains a list object (data fed from a database). Then there are cells contains formulas like the following
this.Range["F15"].Formula = "=COUNTIFS(HotList_ListObject[Product],E15,HotList_ListObject[Got_Interest],\"<>\")"
previously, I created the table by just drag-and-drop. then simply created a formula in the worksheets. and the formulas were recalculated as data in the listobject (HotList_ListObject above).
this time, I created the table by the code. Because Hotlist_ListObject is not on the worksheet until the application runs, I supply the formulas after creating the listobject by code.
I looked through the internet and did a couple of testings.
When I press F9, SHIFT+F9 and CTRL+ALT+F9, it doesn't recalculate.
Only when I press CTRL+SHIFT+ALT+F9, it recalculates
the explantion I found for CTRL+SHIFT+ALT+F9 is
Rechecks dependent formulas, and then calculates all formulas in all open workbooks, regardless of whether they have changed since last time or not.
It seems that because the formula is supplied in the worksheet by code, it does not create links to dependent formulas or something so it won't recalculate. (something like this, I suppose)
My users are not going to press the button every time they modify/add/delete records in the list.
what can I do to resolve this? How to tell Excel that the formulas need to recalculate every-time any thing changes in the listobject.
Thanks for any advice in advance!
Kind regards
Mark

Does setting the Calculation to Manual:
xlApp.Calculation = XlCalculation.xlCalculationManual;
xlApp.ScreenUpdating = false;
xlApp.DisplayAlerts = false;
xlApp.UserControl = false;
xlApp.EnableEvents = false;
Then populating your Hotlist_ListObject (that is not on the worksheet until the application runs and) then set calculation to Automatic:
xlApp.Calculation = XlCalculation.xlCalculationAutomatic;
xlApp.ScreenUpdating = true;
xlApp.DisplayAlerts = true;
xlApp.UserControl = true;
xlApp.EnableEvents = true;
Resolve the problem? If not could you please post some bare bones code to illustrate the issue.

Did you check the options settings? This might be reset to manual by a macro (check with macro editor using Alt+F11 for xlCalculateManual and make sure the macro is not stopped before Application.Calculation = xlCalculationAutomatic is executed to set calaculations back to automatic. Turning calculations off is an often used method to speed macros up, but when a macro is exited half-way, this manual calculation setting will stay.
Here is the manual setting.

Related

EPPlus excel sheet with script text in a cell

I'm coming across an issue that I'm not sure there's a good answer for.
We have a bulk-insert spreadsheet template to allow people to define certain components of an online ad. They then upload the document, we process it, and set it up in the database.
Recently there was a feature request to change bulk-insert into bulk-edit; IOW, people will download an excel sheet with information about the current ad prepopulated in the fields on the sheet. They would make changes as a set, then re-upload and we'd process the changes and update the database.
The problem is, one of the pieces of information is an HTML snippet with a <script> tag, and it seems like Excel pretty much deletes that automatically, so that column is never being populated when pulling down the sheet. It makes sense, in a way; it resembles executable code and could be a serious virus threat under some conditions, but even if I specify the column as pure text (using the Style.NumberFormat = "#" in EPPlus), Excel just makes the entire piece of data go away. It also skews the columns, looks like... shifts the subsequent cells to the left by one cell.
Is there any way to (safely) make this work without requiring changes to the downloader's security settings?
I dont have time to check into this, but What if you saved the workbook as a macro workbook, to enable some of the less secure behavior within the workbook?
One other thing may be to escape the content with a single quote ' in the beginning of the cell, or wrap the entire "script" content with quotes.
What version of excel do you expect to encounter in the wild? I tested this with Excel 2013, and was able to save the following to a workbook, and parse it into a Datatable using EPP Plus 4.1.0.0:
<script type="text/javascript">$(document).ready(function() {var I =0; console.info(I+100);});</script>
'<script type="text/javascript">$(document).ready(function() {var I =0; console.info(I+100);});</script>
"<script type='text/javascript'>$(document).ready(function() {var I =0; console.info(I+100);});</script>"
Nothing fancy, just iterating each cell in the workbook, pulling in the value and converted to string:
object obj = Worksheets[WorkSheetIndex].Cells[k, l].Value;

will Excel UDF gets calculation upon open?

My Excel 2007 is set to Auto Calculation Mode.
I have two Excel files. MyUDF (multiple cells) is used in both files.
When I open one file in Excel, I notice no MyUDF is calculated.
But when I open the other file, all MyUDFs are calculated.
So I am a little confused as when will a UDF be calculated upon open and when not?
MyUDF is a UDF in MyAddIn written in C#
Edit
The two files are open in the same instance of Excel. MyUDF is not volatile.
Thanks
Edit
I found http://social.msdn.microsoft.com/Forums/en-US/b477c05a-ae0a-470c-8ad5-482ecd05944b/xll-addin-does-not-calculate-udf-when-opening-a-workbook?forum=exceldev
It says xla will, xll, vba will not.
hmm, this does not match what I see.
Not necessarily. Something like:
Public Function MYUDF() As Date
Application.Volatile
MYUDF = Now
End Function
will be re-calculated, however something like:
Public Function MYUDF() As Date
MYUDF = Now
End Function
may not be re-calculated.
It might be a good idea to set "automatic calculation" in your workbook's Open event. Something like this inside your ThisWorkbook object (this is important!):
Private Sub Workbook_Open()
Application.Calculation = xlCalculationAutomatic
End Sub
This is just to make sure that the setting is set as you expect within your workbook to avoid relying on what calculation mode your Excel application has in its options/settings. If nothing else, at least it eliminates one possibility for why you are getting this behaviour.
Excel "helpfully" remembers where the function was called from.
With he same function in both spreadsheets, Excel may simply be waiting for the other to open so it can do the calculation. Check the formula in the spreadsheet that does not recalculate, and see if it's changed to something like 'C:\MyDocs\MyOtherSpreadsheet.xlsb'!MyUDF(A1).
If it has, search for the full spreadsheet name (including the extra characters it uses for delimiters) and replace with nothing.
If it hasn't, set the calculation to Automatic. To force a recalculation, either select Recalculate now from the ribbon, press F9, or do a search and replace, and replace all the = with exactly the same.

using Excel Workbooks.OpenXML and getting a warning that stops the automation

Excel 2010.
I have a C# app that has a dataset with multiple tables. I want to export this to a workbook where each table is a separate sheet it is important to keep the order of the datasets, and the name of the data tables)
One possible solution is to loop through each table, put it on its own dataset, save this dataset as XML, then use the Application.Workbooks.OpenXML method
MSDN OpenXML Documentation
But here is the problem, if I pass the third parameter (which gives a very nice import with filters and everything), excel succeed, but it warns me that some columns were imported as text, which is ok with me (one of the columns is UPC, which should be a text, not a number).
By displaying this message it stops the process until the user clicks that this is acceptable. Then I question my self about how the mother of all excels is doing these days.
How to prevent this message from popping up?
Or another way to do this import with such nice results? (Copy and paste works but not so nicely, writing in every cell using automation is way to slow, maybe using some excel library...)
You turn
Try
var excelApplication = new Application { DisplayAlerts = false };
or
Workbook excelWorkBoook = excelApplication.Workbooks.Open(...);
excelWorkBoook.CheckCompatibility = false;

Format as table (TableStyles) in Excel VSTO 2007, error: one table cannot overlap another table

I am making an add-in and I am trying to format the output which my add-in generates,using Format as table table-styles provided by Excel.
The one which you get on the 'home tab' --> 'Format as Table' button on the ribbon.
I am using following code:
SourceRange.Worksheet.ListObjects.Add(XlListObjectSourceType.xlSrcRange,
SourceRange, System.Type.Missing, xlYesNo, System.Type.Missing).Name =
TableName;
SourceRange.Select();
SourceRange.Worksheet.ListObjects[TableName].TableStyle = TableStyleName;
TableStyleName is any style name like TableStyleMedium17, you get it if you just hover a particular style in Excel.
My problem is that, even if I keep the SourceRange as 10 columns, all the columns right till the end get selected and are considered as one table.
Because of that the table I populate right next to it is also considered as a part of the first table that was generated.Since, both the table have same column names excel automatically changes the column names in all the following tables that are generated.
Also, because I am generating the tables in a loop after 2 tables are generated I get the error :
A table cannot overlap another table.
PS: I am clearly mentioning SourceRange as:
var startCell = (Range)worksheet.Cells[startRow, startCol];
var endCell = (Range)worksheet.Cells[endRow, endCol];
var SourceRange = worksheet.get_Range(startCell, endCell);
Kindly suggest a way out.
We were able to figure out what was happening on our end for this:
on the
xlWorkbook.Worksheets.Add([before],[after], Type.Missing, Type.Missing)
call, we had to flip before and after since we wanted the sheets to move right, not left and then accessed
xlWorkbook.Worksheets[sheetCount]
by increasing sheetcount for however many sheets were being generated.
Having it the other way was creating the worksheet to access a previously assigned table formatfrom the SourceRange.Worksheet.ListObjects[TableName].TableStyle = TableStyleName call.
So, I got around this problem a week after posting this, sorry did not update in the rush of things.
This actually is an in built excel functionality.
You cant help it, the excel application will keep doing this.
So, ultimately wrote my own table styles in c# and applied it to the excel range which is mentioned as SourceRange. Its just like writing CSS.
If you are interested in knowing the details of that comment it on this question itself or you can contact me by email from my profile.

Excel Interop - Cancel selection

I'm copying and inserting rows in an Excel sheet, like so:
while (rowsToAdd > 0)
{
// copy the existing row
insertionCell.EntireRow.Copy(Type.Missing);
// location of the new row
Range newRow = insertionCell.EntireRow.get_Offset(1, 0).EntireRow;
// insert the new row
newRow.Insert(XlInsertShiftDirection.xlShiftDown, Type.Missing);
rowsToAdd--;
}
The problem I have is that sometimes, I'm left with a selection marquee around the row I originally copied.
Is there a way I can cancel the selection marquee (the way you'd normally do it with the Escape key?)
In VBA it's Application.CutCopyMode = False
Adding
myExcelApplication.CutCopyMode = XlCutCopyMode.xlCopy;
seems to do the trick, though the documentation does not explain it very well, and seems to be wrong, since bools are mentioned.
I know it's pretty old, but as I had some issue copying one row to another, and as I got the proper solution on my case, I'm now glad to share it, just in case it could fix your problem (thinking about copy rows instead of inserting one).
Here is the solution:
Microsoft.Office.Interop.Excel.Range xlSourceRow;
Microsoft.Office.Interop.Excel.Range xlNewRow;
xlSourceRow.Copy(xlNewRow);
Using this solution prevents from getting any selection in your MS-Excel file.

Categories

Resources