我使用dos .bat文件连续运行.vbs文件...如果发生任何错误,批处理文件会再次运行vbscript并继续运行。该脚本通过互联网连接到一个站点以执行一些api调用。 现在当出现连接问题或任何其他错误时,控件将从脚本中保持打开excel文件。这样许多excel文件在每个错误上都会打开...代码如下...请告诉我如何在出错时关闭excel文件然后优雅地退出脚本。
'{{{{Some coding}}}}
dim objExcel, objWorkbook, objRange
Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("C:\temp.xlsx")
objExcel.Visible = True
'{{{{Some coding}}}}
objExcel.Cells(xlrow, 3).Value="Test"
objExcel.Cells(xlrow, 3).Select
objExcel.Activecell.Show
'{{{{Some coding}}}}
objExcel.Workbooks(1).save
objExcel.Workbooks(1).close
objExcel.Quit
Set objExcel = Nothing
Set objWorkbook = Nothing
WScript.Quit
提前致谢
答案 0 :(得分:2)
一种可能的方法是将Excel处理包装在自定义类中:
Class Excel
Private xl
Private Sub Class_Initialize
Set xl = CreateObject("Excel.Application")
End Sub
Private Sub Class_Terminate
For Each wb In xl.Workbooks
wb.Saved = True 'discard unsaved changes
wb.Close 'close workbook
Next
xl.Quit 'quit Excel
End Sub
Public Function OpenWorkbook(filename)
Set OpenWorkbook = xl.Workbooks.Open(filename)
End Function
Public Function NewWorkbook
Set NewWorkbook = xl.Workbooks.Add
End Function
Public Property Get Workbooks
Set Workbooks = xl.Workbooks
End Property
End Class
每当销毁一个类实例时,都会自动调用过程Class_Terminate
。这样,您可以自动关闭打开的工作簿并退出Excel。
这个类可以像这样使用:
Set xl = New Excel
Set wb = xl.OpenWorkbook("C:\path\to\your.xlsx")
...
wb.Close