I've got this code to conditionally format a cell after it has been assigned to, based on the value it contains:
var avgWeeklyDeliveriesCell = (Excel.Range)_xlSheet.Cells[curDelPerfRow,
AVG_WEEKLY_DELIVERIES_COLUMN];
avgWeeklyDeliveriesCell.Value2 = string.Format("=ROUND(AVERAGE(C{0}:I{0}),
2)", curDelPerfRow);
avgWeeklyDeliveriesCell.NumberFormat = "#,##0.00";
ConditionallyHighlight(avgWeeklyDeliveriesCell.Value2,
_xlSheet.UsedRange.Row);
private void ConditionallyHighlight(string cellVal, int rowIndex)
{
int COL_K_INDEX = 11;
float avgWeeklyDelivery = float.Parse(cellVal,
CultureInfo.InvariantCulture);
if (avgWeeklyDelivery > delsPerWeek)
{
Excel.Range cellToHighlight = (Excel.Range)_xlSheet.Cells[rowIndex
COL_K_INDEX];
cellToHighlight.Interior.Color = OUT_OF_BOUNDS_HIGHLIGHT_COLOR;
}
}
The problem is with cellVal; it seems to be a string, as I'm assigning the results of a String.Format() call to the cells' Value2 property, and then passing that (value2) to the method that is to conditionally format the cell.
It compiles, but at runtime it fails with an "invalid args" message. Why, and how can I fix it?
After you setup the formula to Value2, this property will returns the evaluated value, which is a int/double in this case. So you will not need to parse the value.
Just change the parameter
cellVal
type to double: