-3

Can you help me solve following Error Message:

"Object reference not set to an instance of an object."

I marked the areas I get the error with comments and **

Please see below.

private static void _GenerateWord(string fname, string reportStartDate, string reportEndDate)
        { 
            var word = new Microsoft.Office.Interop.Word.Application();
            var doc = new Microsoft.Office.Interop.Word.Document();
            word.Visible = false;
            object missing = Type.Missing;

            object fileName = (@LetterTemplateLocation + LetterName);

            doc = word.Documents.Open(ref fileName);


            doc.Activate();//**Error message here "Object reference not set to an instance of an object."**

            string dateWithFormat = DateTime.Now.ToString("MMMM d, yyyy");

            //**Error message here "Object reference not set to an instance of an object."**
            foreach (Microsoft.Office.Interop.Word.Range tmpRange in doc.StoryRanges)
            {
                _FindAndReplace("<date>", dateWithFormat, tmpRange, missing);

                _FindAndReplace("<filename>", fname, tmpRange, missing);

                _FindAndReplace("<startdate>", reportStartDate, tmpRange, missing);

                _FindAndReplace("<enddate>", reportEndDate, tmpRange, missing);
            }

            if (doc != null)
            {
                doc.Close(ref missing, ref missing, ref missing);
                word.Application.Quit(ref missing, ref missing, ref missing);
            }
        }

Thank you.

venergiac
  • 7,469
  • 2
  • 48
  • 70
Sam
  • 7
  • 1
  • possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Konrad Kokosa Jan 15 '14 at 21:53
  • 4
    Looks like `doc` get's null. Are your sure `fileName` is a path to an existing word document file? – Idan Arye Jan 15 '14 at 21:53
  • I would check if fileName exist first.. bool found = File.Exist(fileName) – PhillyNJ Jan 15 '14 at 21:57
  • @Idan Arye: Yes, `fileName` is a path to an existing word template. thanks! – Sam Jan 15 '14 at 22:00
  • Why is your fileName typed as object? .Documents.Open takes a string parameter. – Aaron Palmer Jan 15 '14 at 22:02
  • fileName is taking object only. If I change to string I get invalid argument error. – Sam Jan 16 '14 at 14:33
  • Also, I am not sure why people voted I didn't research before I posted the question. I researched for hours didn't find/understand any solution that can help. Maybe some people are more experience in finding the answers because those people knows what to look for. I am here because I am a noob trying to learn. – Sam Jan 16 '14 at 14:39

1 Answers1

0

As a practice need to check doc for null.

If(doc !=null){...}

Also need to evaluate valid file, as others suggested.

Adi Barman
  • 13
  • 3