通过vb代码打开一个Excel模版,然后修改其中单元格的颜色后,把excel关掉后,任务管理器还是有一个Excel进程。而且不退出程序,第二次跑代码就会出错,求高手指点,谢谢了!代码如下://创建对象
Public appReport As Excel.Application
Public wbReport As Excel.Workbook
Public shtReport As Excel.Worksheet
Public rngReport As Excel.RangeSet appReport = CreateObject("Excel.Application")
Set wbReport = appReport.Workbooks.Open(XlsName)
Set shtReport = wbReport.Sheets(1)
Set rngReport = shtReport.Columns(1)//改变表格颜色
Range(A3:Q3).Select
With Selection.Interior
.ColorIndex = 36
End With//省略一堆代码。。//关闭对象
wbReport.SaveAs ToFileName
wbReport.Close False
Set rngReport = Nothing
Set shtReport = Nothing
Set appReport = Nothing
Set wbReport = Nothing
Public appReport As Excel.Application
Public wbReport As Excel.Workbook
Public shtReport As Excel.Worksheet
Public rngReport As Excel.RangeSet appReport = CreateObject("Excel.Application")
Set wbReport = appReport.Workbooks.Open(XlsName)
Set shtReport = wbReport.Sheets(1)
Set rngReport = shtReport.Columns(1)//改变表格颜色
Range(A3:Q3).Select
With Selection.Interior
.ColorIndex = 36
End With//省略一堆代码。。//关闭对象
wbReport.SaveAs ToFileName
wbReport.Close False
Set rngReport = Nothing
Set shtReport = Nothing
Set appReport = Nothing
Set wbReport = Nothing
appReport.quit
Public appReport As Excel.Application
Public wbReport As Excel.Workbook
Public shtReport As Excel.Worksheet
Public rngReport As Excel.RangeSet appReport = CreateObject("Excel.Application")
Set wbReport = appReport.Workbooks.Open(XlsName)
Set shtReport = wbReport.Sheets(1)
Set rngReport = shtReport.Columns(1)//改变表格颜色
Range(A3:Q3).Select
With Selection.Interior
.ColorIndex = 36
End With//省略一堆代码。。//关闭对象
wbReport.SaveAs ToFileName
wbReport.Close False
appReport.quit '结束excel对象
Set rngReport = Nothing
Set shtReport = Nothing
Set wbReport = Nothing '这两个颠倒一下,这样更符合大小逻辑
Set appReport = Nothing
另外,一般情况下加上错误处理的好,释放对象的顺序最好"从内到外".比如
errHandle:
'不覆盖时释放对象
appReport.DisplayAlerts = False
wbReport.Close
appReport.DisplayAlerts = True
Set rngReport = Nothing
Set shtReport = Nothing
Set wbReport = Nothing
Set appReport= Nothing
Range(A3:Q3).Select
With Selection.Interior
.ColorIndex = 36
End With
改成
shtReport.Range(A3:Q3).Interior.ColorIndex = 36
shtReport.UsedRange.Interior.Color = vbBlue