Solved

MS Word Automation problem - Error:"Use of unassigned local variable oDoc"

Posted on 2006-06-18
3
632 Views
Last Modified: 2008-02-01
Hello,

Got a frustrating problem here.

Here's what I'm trying to do:
-grab some data from a db store it into a dataset.
-iterate through dataset, writing 3 records at a time to a word doc, then save the file.
-then create a new word doc..grab 3 more records, create a new file..etc...until there is no more records in the dataset.


The code worked great when dealing with a single record, but after adding the loop and the logic to only write out 3 recs per file, I get the following compile time error:
"Use of unassigned local variable'oDoc'" at this line in the code "oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing);"


I believe this is occurring because I am implicitly creating an instance of the document by using the "add method" on the application object, and "oDoc" is now not in scope because it's defined within the "if block",  but I'm not really sure how to get this work though.

Here is a simplified version of the code, using a for loop. Any ideas would be greatly appreciated.

Thanks


       private void button2_Click(object sender, EventArgs e)
        {
            object oMissing = System.Reflection.Missing.Value;
           Word._Application oWord;
            Word._Document oDoc;
            oWord = new Word.Application();
            Word.Paragraph oPara1;
            oWord.Visible = true;

            int fileNameCounter = 0;
            int numOfItems = 0;
          
            for (int i = 0; i < 12; i++)
            {
                numOfItems++;

                if (numOfItems == 1)
                {
                    oDoc = oWord.Documents.Add(ref oMissing, ref oMissing,
                    ref oMissing, ref oMissing);
                }

                //Insert a paragraph at the beginning of the document.
                oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing);
                oPara1.Range.Text = ""WRITE A RECORD TO WORD";
                oPara1.Range.InsertParagraphAfter();


                if (numOfItems == 3)
                {
          fileNameCounter++;

                    string filePath = @"C:\_Temp\Test" + fileNameCounter + ".DOC";
                    object filePath2 = (object)filePath;
                    oDoc.SaveAs(ref filePath2,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing);

                    //Release the reference.
                   
                    oWord = null;
                }
                oWord.Quit(ref oMissing, ref oMissing, ref oMissing);
               
            } //ends for loop

            MessageBox.Show("files created");
               
           
        }
0
Comment
Question by:rfrankson
  • 2
3 Comments
 
LVL 7

Accepted Solution

by:
dttri earned 500 total points
ID: 16932611
Greetings,
I think this block of code causes the compile time error:
<<<<<<
    if (numOfItems == 1)
                {
                    oDoc = oWord.Documents.Add(ref oMissing, ref oMissing,
                    ref oMissing, ref oMissing);
                }

                //Insert a paragraph at the beginning of the document.
                oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing);
                oPara1.Range.Text = ""WRITE A RECORD TO WORD";
                oPara1.Range.InsertParagraphAfter();
>>>>>>>>
As you can see, if numOfItems isn't equal to 1, then oDoc is not initialized, and then the line "oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing);" will cause the error because it access the content of the unassigned variable oDoc.

Try to change the code to the block below to see if this help:

<<<<CODE>>>>>>>>>
private void button2_Click(object sender, EventArgs e)
        {
            object oMissing = System.Reflection.Missing.Value;
            Word._Application oWord;
            Word._Document oDoc;
            oWord = new Word.Application();
            Word.Paragraph oPara1;
            oWord.Visible = true;

            int fileNameCounter = 0;
            int numOfItems = 0;

            oDoc = oWord.Documents.Add(ref oMissing, ref oMissing,
                    ref oMissing, ref oMissing);   //add this line so that the compiler don't warning the "use of unassigned local variable"
         
            for (int i = 0; i < 12; i++)
            {
                numOfItems++;

                if (numOfItems == 1)
                {
                    oDoc = oWord.Documents.Add(ref oMissing, ref oMissing,
                    ref oMissing, ref oMissing);
                }

                //Insert a paragraph at the beginning of the document.
                oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing);
                oPara1.Range.Text = ""WRITE A RECORD TO WORD";
                oPara1.Range.InsertParagraphAfter();


                if (numOfItems == 3)
                {
                   fileNameCounter++;
                   numOfItems=0;           //reset the numOfItems variable to zero for the next document

                   string filePath = @"C:\_Temp\Test" + fileNameCounter + ".DOC";
                   object filePath2 = (object)filePath;
                   oDoc.SaveAs(ref filePath2,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing);
                }
               
            } //ends for loop

            MessageBox.Show("files created");
        }
<<<<END CODE>>>>>>>>>
0
 

Author Comment

by:rfrankson
ID: 16934116
Thank you very much dttri, that did the trick.
0
 
LVL 7

Expert Comment

by:dttri
ID: 16935245
You're welcome! And thanks for the point!
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
bulid json format 3 46
C# replace string in void with dR["myData"].ToString() 3 42
Name space syntax error 12 44
Error on Add method 1 38
Extention Methods in C# 3.0 by Ivo Stoykov C# 3.0 offers extension methods. They allow extending existing classes without changing the class's source code or relying on inheritance. These are static methods invoked as instance method. This…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Internet Business Fax to Email Made Easy - With  eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, f…
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.

862 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

24 Experts available now in Live!

Get 1:1 Help Now