当我将其设置为activeworkbook时,为什么我的Workbook对象为空?

我曾经见过类似的问题,但是我发现没有一个能解决我的具体情况。

我在Visual Studio 2010中有一个Excel 2007 COM加载项,用C#编写。 当我将活动手册加载到function区代码中的工作簿对象时,它工作正常。 当我以Windows窗体的forms进行操作时,每次都会从activeworkbook中返回null。

以下是我的使用语句和错误不断发生的代码片段。

using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using Office = Microsoft.Office.Core; using System.Windows.Forms; using Excel = Microsoft.Office.Interop.Excel; using System.Drawing; --------------------------------------------------- Excel.Application xlApp; xlApp = (Excel.Application)Marshal.GetActiveObject("Excel.Application"); Excel.Workbook xlWkbk = (Excel.Workbook)xlApp.ActiveWorkbook; Excel.Worksheet xlWksht = (Excel.Worksheet)xlWkbk.ActiveSheet; 

任何帮助将不胜感激!

只要您的任务pipe理器有1个EXCEL.EXE进程列出 ,代码本身的工作时间很长

我怀疑你正在testing的东西,并没有正确处置EXCEL.EXE或没有error handling,因此你元帅到错误的EXCEL.EXE过程。

添加一个error handling程序并按照本答案正确处理Excel。