我正在使用带有 .net 4.0 Framework 和 Office 2010 的 c#
我目前正在尝试弄清楚如何关闭已经打开的 word 文档。我在这段代码中遇到了错误:
Microsoft.Office.Interop.Word.Application app = (Microsoft.Office.Interop.Word.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");
foreach (Microsoft.Office.Interop.Word.Document d in app.Documents)
{
if (d.FullName.ToLower() == "OOPOR".ToLower())
{
object saveOption = WdSaveOptions.wdPromptToSaveChanges;
object originalFormat = WdOriginalFormat.wdOriginalDocumentFormat;
object routeDocument = false;
d.Application.Documents.Close(ref saveOption, ref originalFormat, ref routeDocument);
}
}
目前,当我运行此代码时,我无法进入 foreach 循环。app.Documents 显示计数为“0”。如果我在 foreach 循环中设置断点并查看“app”变量,它会指出:
ActiveDocument = '((Microsoft.Office.Interop.Word.ApplicationClass)(app)).ActiveDocument' threw an exception of type 'System.Runtime.InteropServices.COMException' >>
base {System.Runtime.InteropServices.ExternalException} = {"This command is not available because no document is open."}
即使我有一个活动的 Word 文档,也会发生这种情况。