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

天涯浪子 提交于 2019-12-05 02:29:37

问题


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));
        }

回答1:


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...
    }
}



回答2:


Does it work with

(object[,])range.get_Value(System.Reflection.Missing.Value);


来源:https://stackoverflow.com/questions/7383304/object-range-get-valuexl-xlrangevaluedatatype-xlrangevaluedefault-causes-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!