MS Word Automation problem - Error:"Use of unassigned local variable oDoc"
Posted on 2006-06-18
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.
private void button2_Click(object sender, EventArgs e)
object oMissing = System.Reflection.Missing.Value;
oWord = new Word.Application();
oWord.Visible = true;
int fileNameCounter = 0;
int numOfItems = 0;
for (int i = 0; i < 12; i++)
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";
if (numOfItems == 3)
string filePath = @"C:\_Temp\Test" + fileNameCounter + ".DOC";
object filePath2 = (object)filePath;
//Release the reference.
oWord = null;
oWord.Quit(ref oMissing, ref oMissing, ref oMissing);
} //ends for loop