B. Clay Shannon February 2016

Why do I get "Invalid args" at runtime with this code?

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?

Answers


Shnugo February 2016

In this line you are passing in a Value2

ConditionallyHighlight(avgWeeklyDeliveriesCell.Value2, _xlSheet.UsedRange.Row);

But the Value2 is a Range-object in Excel and - maybe - not directly useable in C#.

Have a look to D Stanley's comment (Thx!) who cleard this point.

Here is a somehow related question: Casting Range.Value2 of Excel interop to string

Try to add a ".ToString()" after Value2 and be aware of the possibilities of "null". Better use float.TryParse()

string YourString = "ImpossibleValue";
float f;
if (!float.TryParse(YourString, out f)) {
    //React on the failed parsing (default value, error... 
}
//go ahead with f, which holds the correct (or defaulted) value

Here's some background: https://msdn.microsoft.com/en-us/library/office/ff193553.aspx


Arturo Menchaca February 2016

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:

private void ConditionallyHighlight(double cellVal, int rowIndex)
{
    int COL_K_INDEX = 11;
    if (cellVal > delsPerWeek)
    {
        Excel.Range cellToHighlight = (Excel.Range)_xlSheet.Cells[rowIndex,
            COL_K_INDEX];
        cellToHighlight.Interior.Color = OUT_OF_BOUNDS_HIGHLIGHT_COLOR;
    }
}

Post Status

Asked in February 2016
Viewed 2,023 times
Voted 13
Answered 2 times

Search




Leave an answer