Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
777 views
in Technique[技术] by (71.8m points)

vbscript - How to exit gracefully closing open excel file on error?

I use dos .bat file to run a .vbs file continuously ... If any error occurs the batch file runs the vbscript again and it goes on. The script connects via internet to a site to execute some api calls. Now when there is connection problem or any other error then the control comes out of the script keeping the excel file open. This way many excel files gets open on each error ... The code is as follows ... please advice me how to close the excel file on error and then come out of the script gracefully.

       '{{{{Some coding}}}}

dim objExcel, objWorkbook, objRange
Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("C:emp.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

Thanks in advance

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

One possible approach is to wrap the Excel handling in a custom class:

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

The procedure Class_Terminate is automatically called whenever a class instance is destroyed. That way you can automatically close the open workbooks and quit Excel.

The class can be used like this:

Set xl = New Excel
Set wb = xl.OpenWorkbook("C:pathoyour.xlsx")
...
wb.Close

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...