C# 异常用户未处理
C# Exception User-Unhandled
我正在构建一个 C# Excel 附加组件以将字符串 xxx
替换为 yyy
并在给定的文件夹路径中批量查找文件:
string replace = "xxx";
string replacement = "yyy";
foreach (FileInfo file in listOfFiles)
{
foreach (Excel.Worksheet xlWorkSheet in xlWorkBook.Worksheets)
{
Excel.Range r = (Excel.Range)xlWorkSheet.UsedRange;
Excel.Range first = r.Find(replace, m, m, Excel.XlLookAt.xlPart, Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlNext, m, m, m);
if (first != null)
{
count++;
Excel.Range start = first;
do
{
start.Value = replacement;
count++;
start = r.FindNext(m);
xlWorkBook.Save();
}
while (start != first);
}
}
xlWorkBook.Close();
}
但是当我 运行 代码时,start.Value = replacement
弹出
错误
System.NullReferenceException
HResult=0x80004003
Message=Object reference not set to an instance of an object.
Source=<Cannot evaluate the exception source>
StackTrace:
<Cannot evaluate the exception stack trace>
我在这里的代码没有发现任何问题。我在设置start
之前已经检查过(first != null)
,所以start
不会为null。
是的,您检查是否为空,但您还有可能导致空的第二个操作。
当没有其他匹配项
时,该行将return 为空
start = r.FindNext(m);
您应该在每次重新分配 start
变量后进行检查。
我正在构建一个 C# Excel 附加组件以将字符串 xxx
替换为 yyy
并在给定的文件夹路径中批量查找文件:
string replace = "xxx";
string replacement = "yyy";
foreach (FileInfo file in listOfFiles)
{
foreach (Excel.Worksheet xlWorkSheet in xlWorkBook.Worksheets)
{
Excel.Range r = (Excel.Range)xlWorkSheet.UsedRange;
Excel.Range first = r.Find(replace, m, m, Excel.XlLookAt.xlPart, Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlNext, m, m, m);
if (first != null)
{
count++;
Excel.Range start = first;
do
{
start.Value = replacement;
count++;
start = r.FindNext(m);
xlWorkBook.Save();
}
while (start != first);
}
}
xlWorkBook.Close();
}
但是当我 运行 代码时,start.Value = replacement
弹出
System.NullReferenceException
HResult=0x80004003
Message=Object reference not set to an instance of an object.
Source=<Cannot evaluate the exception source>
StackTrace:
<Cannot evaluate the exception stack trace>
我在这里的代码没有发现任何问题。我在设置start
之前已经检查过(first != null)
,所以start
不会为null。
是的,您检查是否为空,但您还有可能导致空的第二个操作。
当没有其他匹配项
start = r.FindNext(m);
您应该在每次重新分配 start
变量后进行检查。