Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(object[,])range.get_Value(XL.XlRangeValueDataType.xlRangeValueDefault) causes a conversion error

Error:

Cannot convert type 'string' to 'object[*,*]'

That's the error I have been getting. Can someone give me some pointers so that I can avoid it? Thanks.

Note:

Interestingly, (object[,])range.get_Value(XL.XlRangeValueDataType.xlRangeValueDefault)

will only produce this bug when range.Count == 1. It works fine when count is equal to and above 2.

sample code:

object[,] arrValue;  //global variable

private string[] createFormulaCollection()
        {
            ArrayList s = new ArrayList();
            try
            {
                //look at the currently active excel sheet
                //iterate through cells (not Null) and find the one contains IES(...)
                //save it into the arraylist
                //use dictionary to save position and value (position as key)
                workbook = Globals.ThisAddIn.Application.ActiveWorkbook;
                worksheet = Globals.ThisAddIn.Application.ActiveSheet;
                range = worksheet.UsedRange;

                MessageBox.Show(range.Count.ToString());


                if (range.Count > 1)
                {
                    //need to make sure there are at least 2 "ies" cells before converting to object[,]
                    arrValue = (object[,])range.get_Value(XL.XlRangeValueDataType.xlRangeValueDefault); 
                }
                else
                {
                    arrValue[1,1] = range.get_Value(XL.XlRangeValueDataType.xlRangeValueDefault); //my try here. seems still got problem though.
                }


            catch (Exception ex)
            {

            }
            return (string[])s.ToArray(typeof(string));
        }
like image 254
woodykiddy Avatar asked Mar 31 '26 21:03

woodykiddy


1 Answers

Finding:

range.get_Value(XL.XlRangeValueDataType.xlRangeValueDefault); will return a string when range.Count == 1 which means it can't be converted to object[,] type.

it can, however, when range.Count > 1.

My workaround:

Just deal with it separately. So in my case I had to first count the number of range object and process them accordingly.

if(range.Count > 1)
{
    //code...
}
else
{
    string singleStrValue = range.get_Value(XL.XlRangeValueDataType.xlRangeValueDefault);
    int iRow, iCol;
    iRow = range.Row;
    iCol = range.Column;
    if (!string.IsNullOrEmpty(singleStrValue))
    {
        //code...
    }
}
like image 169
woodykiddy Avatar answered Apr 03 '26 09:04

woodykiddy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!