您能否帮我解决错误消息:
“对象引用未设置为对象的实例。”
我通过评论和**
请参阅下文。
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);
}
}
谢谢。
答案 0 :(得分:0)
作为一种做法,需要检查doc for null。
如果(doc!= null){...}
还需要像其他人建议的那样评估有效文件。