【发布时间】:2011-09-12 04:24:18
【问题描述】:
错误:
Cannot convert type 'string' to 'object[*,*]'
这就是我遇到的错误。有人可以给我一些指示,以便我可以避免它吗?谢谢。
注意:
有趣的是,(object[,])range.get_Value(XL.XlRangeValueDataType.xlRangeValueDefault)
只有在range.Count == 1 时才会产生这个错误。当 count 等于或大于 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.Count == 1 时才会发生错误是有道理的,因为 Range 指的是特定的单元格,而 get_Value 返回该单元格的值。
-
但是,您提到的错误不应该出现在您发布的代码中,因为您正在专门处理 range.Count == 1 的情况。
-
是的,这只是我的尝试。我想捕获 range.Count == 1 的特定情况,这样它就不会无意中抛出异常。但是我上面的方法不太正确,因为您正在进行字符串 -> 对象数组转换。
-
我不关注。如果在您分配给 arrValue[1,1] 时已实例化 arrValue,那么我可以从您发布的代码中收集到的内容应该没有问题。那么您到底遇到了什么问题?
-
不,如果 range.Count == 1 是不正确的。但是您已经处理了这种情况。由于它是一个对象数组,因此您可以在其中放置任何值,即
arrValue[1,1] = range.get_Value(...)不应失败。看来您已经解决了您要求我们帮助您解决的问题...?
标签: c# .net excel interop excel-interop