gpt4 book ai didi

c# - (object[,])range.get_Value(XL.XlRangeValueDataType.xlRangeValueDefault) 导致转换错误

转载 作者:行者123 更新时间:2023-11-30 18:03:16 25 4
gpt4 key购买 nike

错误:

无法将类型“string”转换为“object[*,*]”

这就是我遇到的错误。有人可以给我一些指示,以便我可以避免吗?谢谢。

注意:

有趣的是,(object[,])range.get_Value(XL.XlRangeValueDataType.xlRangeValueDefault)

仅当 range.Count == 1 时才会产生此错误。当计数等于或大于 2 时,它工作正常。

示例代码:

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

最佳答案

发现:

range.get_Value(XL.XlRangeValueDataType.xlRangeValueDefault); 将在 range.Count == 1 时返回一个字符串这意味着它不能转换为 object[,] 类型。

但是,当 range.Count > 1 时,它可以。

我的解决方法:

单独处理即可。所以在我的例子中,我必须首先计算范围对象的数量并相应地处理它们。

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

关于c# - (object[,])range.get_Value(XL.XlRangeValueDataType.xlRangeValueDefault) 导致转换错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7383304/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com