检查 Cell 是否为空以中断 while 循环
Check if Cell is empty to break while loop
你好,我正在研究一种从单元格中提取数据的方法。这行得通,但每次我到达一个空单元格时,我都会得到一个 NullBinderException
.
我的问题是如何防止这种情况发生?
这里是出问题的部分:
while ((range.Cells[startpoint, cell] as Excel.Range).Value2.ToString() != null)
{
for (int i = 1; i <= numberOfColumns; i++)
{
string sValue = (range.Cells[startpoint, cell] as Excel.Range).Value2.ToString();
stringList.Add(sValue);
cell++;
}
startpoint++;
cell = 1;
}
我试过的东西:
range.Offset
= 不能使用,因为这不是可用的会员。
IsNullOrEmpty
= 没有区别
所以有些东西我不明白。任何帮助或建议都将非常有用,感谢您的宝贵时间。
您可以将 while 循环设为:-
while (! IsNull(range.Cells[startpoint, cell] as Excel.Range).Value2))
单元格范围and/or Value2 可能为空。在您的 Where 子句中检查这些。
while ((range.Cells[startpoint, cell] as Excel.Range) != null && (range.Cells[startpoint, cell] as Excel.Range).Value2 != null)
{
for (int i = 1; i <= numberOfColumns; i++)
{
string sValue = (range.Cells[startpoint, cell] as Excel.Range).Value2.ToString();
stringList.Add(sValue);
cell++;
}
startpoint++;
cell = 1;
}
你可以试着捕捉你的异常:
try
{
while ((range.Cells[startpoint, cell] as Excel.Range).Value2.ToString() != null)
{
for (int i = 1; i <= numberOfColumns; i++)
{
string sValue = (range.Cells[startpoint, cell] as Excel.Range).Value2.ToString();
stringList.Add(sValue);
cell++;
}
startpoint++;
cell = 1;
}
}
catch(nullBinderException e)
{
//you find an empty cell
//... break? jump over and continue?
//... your logic...
}
你好,我正在研究一种从单元格中提取数据的方法。这行得通,但每次我到达一个空单元格时,我都会得到一个 NullBinderException
.
我的问题是如何防止这种情况发生?
这里是出问题的部分:
while ((range.Cells[startpoint, cell] as Excel.Range).Value2.ToString() != null)
{
for (int i = 1; i <= numberOfColumns; i++)
{
string sValue = (range.Cells[startpoint, cell] as Excel.Range).Value2.ToString();
stringList.Add(sValue);
cell++;
}
startpoint++;
cell = 1;
}
我试过的东西:
range.Offset
= 不能使用,因为这不是可用的会员。
IsNullOrEmpty
= 没有区别
所以有些东西我不明白。任何帮助或建议都将非常有用,感谢您的宝贵时间。
您可以将 while 循环设为:-
while (! IsNull(range.Cells[startpoint, cell] as Excel.Range).Value2))
单元格范围and/or Value2 可能为空。在您的 Where 子句中检查这些。
while ((range.Cells[startpoint, cell] as Excel.Range) != null && (range.Cells[startpoint, cell] as Excel.Range).Value2 != null)
{
for (int i = 1; i <= numberOfColumns; i++)
{
string sValue = (range.Cells[startpoint, cell] as Excel.Range).Value2.ToString();
stringList.Add(sValue);
cell++;
}
startpoint++;
cell = 1;
}
你可以试着捕捉你的异常:
try
{
while ((range.Cells[startpoint, cell] as Excel.Range).Value2.ToString() != null)
{
for (int i = 1; i <= numberOfColumns; i++)
{
string sValue = (range.Cells[startpoint, cell] as Excel.Range).Value2.ToString();
stringList.Add(sValue);
cell++;
}
startpoint++;
cell = 1;
}
}
catch(nullBinderException e)
{
//you find an empty cell
//... break? jump over and continue?
//... your logic...
}