C# Exception User-Unhandled

1

I am building a C# Excel Add-on to replace string xxx to yyy and find files in batch in a given folder path:

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

But when I run the code, the start.Value = replacement pops an error of

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>

I don't see any problems with my code here. I already check if (first != null) before setting up start, so start will not be null.

c#
excel
vsto
asked on Stack Overflow Dec 17, 2019 by Isaak Newton

1 Answer

2

Yes, you check for null, but you also have 2nd action which may lead to null.
This line will return null when there are no other matches

 start = r.FindNext(m);         

You should do your check after each re-asign of the start variable.

answered on Stack Overflow Dec 17, 2019 by vasil oreshenski

User contributions licensed under CC BY-SA 3.0