A
Arturo
Hello everybody. Can someone have a look at this bit of code?
Private Sub TestExcel()
'Create the Excel Application
Dim xlExcel As Application = New Excel.Application
xlExcel.DisplayAlerts = False
Dim xlWorkbooks As Workbooks = xlExcel.Workbooks
Try
Dim xlWorkbook As Workbook = xlWorkbooks.Open("D:\Test.xls")
Try
Dim xlWorksheets As Sheets = CType(xlWorkbook.Worksheets,
Sheets)
Dim xlWorksheet As Worksheet
For Each xlWorksheet In xlWorksheets
xlWorksheet = Nothing
Next
xlWorksheets = Nothing
Finally
xlWorkbook.Close()
xlWorkbook = Nothing
End Try
Finally
xlWorkbooks = Nothing
xlExcel.Quit()
xlExcel = Nothing
GC.Collect()
End Try
End Sub
....You will get an error from excel saying "Memory could not be read".
If you change the "For Each" and put a standard For iX = 1 To
xlWorksheets.Count the problem goes away. Any explanation? I think
is the way For Each gets the enumerator, but I don't know. I need to
use automation a lot, and I would like to know what is the real
behaviuor of excel in this case.
Thanks a lot.
Arturo
Private Sub TestExcel()
'Create the Excel Application
Dim xlExcel As Application = New Excel.Application
xlExcel.DisplayAlerts = False
Dim xlWorkbooks As Workbooks = xlExcel.Workbooks
Try
Dim xlWorkbook As Workbook = xlWorkbooks.Open("D:\Test.xls")
Try
Dim xlWorksheets As Sheets = CType(xlWorkbook.Worksheets,
Sheets)
Dim xlWorksheet As Worksheet
For Each xlWorksheet In xlWorksheets
xlWorksheet = Nothing
Next
xlWorksheets = Nothing
Finally
xlWorkbook.Close()
xlWorkbook = Nothing
End Try
Finally
xlWorkbooks = Nothing
xlExcel.Quit()
xlExcel = Nothing
GC.Collect()
End Try
End Sub
....You will get an error from excel saying "Memory could not be read".
If you change the "For Each" and put a standard For iX = 1 To
xlWorksheets.Count the problem goes away. Any explanation? I think
is the way For Each gets the enumerator, but I don't know. I need to
use automation a lot, and I would like to know what is the real
behaviuor of excel in this case.
Thanks a lot.
Arturo