Search code examples
excelvbalong-running-processes

How can I execute a long running process in VBA without making pc crawl?


I have a VBA application that creates an instance of a COM object and then continuously polls the objects DataReady property to see if there is new data. When new data is available it sticks the data into a spread sheet. The problem is this macro (vba sub routine) continually runs and this slows down excel to a crawl and makes the computer somewhat unusable while the process is running. Is there a way that I can start this process on a separate thread or do something like a .NET background worker?

My two attempts were to use a while loop like this..

While(True)
    If(myObject.DataReady)
        Do some stuff here
    End If
WEnd

and then this

Sub GrabNewPoint()
If (myModule.NewDataReady_Receiver = True) Then
            Do some stuff here...
End If

If (StopTest = False) Then
    NextTime = Now() + TimeValue("00:00:20")
    Application.OnTime NextTime, "GrabNewPoint"
End If

The second attempt definitly works better but it still slows things down considerably. Is there a better solution?

My COM object is a class library that I wrote in C#. I can add events that fire in the Class Library when data is ready but how do I listen for those events in the VBA program?


Solution

  • Have you tried using DoEvents?

    While(True)
        If(myObject.DataReady)
            'your code here
        End If
        DoEvents
    WEnd