Using Excel from Threads

  • Thread starter Thread starter sfeinst
  • Start date Start date
S

sfeinst

I am trying to access Excel spreadsheets to modify data from a VB.NET
application. If I have an object defined as:

Public Class Test
Private _excel As Microsoft.Office.Interop.Excel.Application
Public Property ExcelApp() As
Microsoft.Office.Interop.Excel.Application
Get
Return _excel
End Get
Set(ByVal Value As Microsoft.Office.Interop.Excel.Application)
_excel = Value
End Set
End Property
Public Sub Process()
Dim oBook As Microsoft.Office.Interop.Excel.Workbook
do somethings here before using excel
oBook = _excel.Workbooks.Open("myfile.xls")
do something with oBook
End Sub
End Class

and access like:
Dim otest As New Test
otest.ExcelApp = New Microsoft.Office.Interop.Excel.Application
otest.Process()

This works fine. But if I try to use a thread like:
Dim otest As New Test
otest.ExcelApp = New Microsoft.Office.Interop.Excel.Application
Dim t As New System.Threading.Thread(AddressOf otest.Process)
t.Start()

the code dies. I'm tracing it through with the debugger. The code
gets to the line:
oBook = _excel.Workbooks.Open("myfile.xls")
and when I press F10 and it never comes back.


Is there an issue with using threads and Excel? I've tested using
just one thread so I don't think it is a deadlock issue.

Thanks for any help,

Steve
 
Is there an issue with using threads and Excel?

Basically you should only use the Excel objects from the same thread
they were created on, and that thread should be an STA thread (see the
Thread.ApartmentState property).


Mattias
 
Basically you should only use the Excel objects from the same thread
they were created on, and that thread should be an STA thread (see the
Thread.ApartmentState property).

Mattias

Thanks. Opening Excel in the thread and using the STA thread seemed
to solve the problem (now I just need to decide if the overhead of
opening excel multiple times is worth using threads for this).

Steve
 
Back
Top