我在2小時前創建了這個程序,當我將這個文件對準presaved .xls文件時,它運行得很順利。但是當我關閉它並開始新實例時,它開始生成空引用異常,爲什麼?PLZ解釋。行爲的變化和空引用異常的產生
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;
using Microsoft.Office.Interop;
using Excel = Microsoft.Office.Interop.Excel;
namespace svchost
{
class MainClass
{
Excel.Application oExcelApp;
static void Main(string[] args)
{
MainClass mc = new MainClass();
while (true)
{
if (mc.chec())
{
Console.WriteLine("RUNNING");
Thread.Sleep(4000);
}
else
{
Console.WriteLine("NOT RUNNING");
Thread.Sleep(8000);
}
}
}
public bool chec()
{
try
{
oExcelApp = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
Excel.Workbook xlwkbook = (Excel.Workbook)oExcelApp.ActiveWorkbook;
//****PROBLEM FROM HERE*********
Console.WriteLine(xlwkbook.Name + "\n");
ke kw = new ke(ref oExcelApp,ref xlwkbook);
Console.WriteLine(xlwkbook.Author);
xlwkbook = null;
}
catch (Exception ec)
{
oExcelApp = null;
System.GC.Collect();
Console.WriteLine(ec);
return false;
}
oExcelApp = null;
System.GC.Collect();
return true;
}
}
class ke
{
public ke(ref Excel.Application a1, ref Excel.Workbook b1)
{
Excel.Worksheet ws = (Excel.Worksheet)a1.ActiveSheet;
Console.WriteLine(a1.ActiveWorkbook.Name + "\n" + ws.Name);
Excel.Range rn;
rn = ws.Cells.Find("657/07", Type.Missing, Excel.XlFindLookIn.xlValues, Excel.XlLookAt.xlPart,
Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlNext, false, Type.Missing, Type.Missing);
Console.WriteLine(rn.Text);
}
}
}
請閱讀:http://stackoverflow.com/editing-help並請重新格式化您的代碼。 – spender
異常發生在哪一行? –
@spender:爲他修好了。 – Kredns